我有一个名为的 JSON 文件test.json,其中包含:
[
{
"name" : "john",
"interests" : ["hockey", "jockey"]
},
{
"name" : "lima",
"interests" : ["eating", "poker"]
}
]
现在我编写了一个 golang 脚本,它将 JSON 文件读取到结构切片中,然后在进行条件检查时,通过迭代切片来修改结构字段。
这是我迄今为止尝试过的:
package main
import (
"log"
"strings"
"io/ioutil"
"encoding/json"
)
type subDB struct {
Name string `json:"name"`
Interests []string `json:"interests"`
}
var dbUpdate []subDB
func getJSON() {
// open the file
filename := "test.json"
val, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(val, &dbUpdate)
}
func (v *subDB) Change(newresponse []string) {
v.Interests = newresponse
}
func updater(name string, newinterest string) {
// iterating over the slice of structs
for _, item := range dbUpdate {
// checking if name supplied matches to the current struct
if strings.Contains(item.Name, name) {
flag := false // declare a flag variable
// item.Interests is a slice, so we iterate over it
for _, intr := range item.Interests {
// check if newinterest is within any one of slice value
if strings.Contains(intr, newinterest) {
flag = true
break // if we find one, we terminate the loop
}
}
// if flag is false, then we change the Interests field
// of the current struct
if !flag {
// Interests holds a slice of strings
item.Change([]string{newinterest}) // passing a slice of string
}
}
}
}
func main() {
getJSON()
updater("lima", "jogging")
log.Printf("%+v\n", dbUpdate)
}
我得到的输出是:
[{Name:john Interests:[hockey jockey]} {Name:lima Interests:[eating poker]}]
但是我应该得到如下输出:
[{Name:john Interests:[hockey jockey]} {Name:lima Interests:[jogging]}]
我的理解是,既然Change()传了一个指针,就应该直接修改字段。谁能指出我做错了什么?
一只甜甜圈
相关分类