英文:
Pointer to slice of interfaces in function parameter
问题
我有以下函数:
func read(filePath string, structure *[]interface{}) {
raw, err := ioutil.ReadFile(filePath)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
json.Unmarshal(raw, structure)
}
我像这样调用它:
indexes := []Index{}
read(path + "/" + element + ".json", &indexes)
然而,当我从函数声明中删除structure *[]interface{}
时,我得到一个奇怪的错误:
./index.verb.go:73: syntax error: unexpected ), expecting {
我认为在尝试传递一个指向通用类型切片的指针时出了问题。那么我应该如何做呢?我不能使用structure *[]Index
,因为我还想返回其他类型。
英文:
I have the following function:
func read(filePath string, structure *[]interface) {
raw, err := ioutil.ReadFile(filePath)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
json.Unmarshal(raw, structure)
}
Which I call like this:
indexes := []Index
read(path + "/" + element + ".json", &indexes)
However, I'm getting strange error that vanish when I take off structure *[]interface
from the function declaration:
./index.verb.go:73: syntax error: unexpected ), expecting {
I think something wront when I try to pass a pointer to a slice of generic type. How should I do it then? I can't do structure *[]Index
because there are other types I wanna return too
答案1
得分: 0
声明函数如下:
func read(filePath string, structure interface{}) error {
raw, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
return json.Unmarshal(raw, structure)
}
structure
值会传递给 json.Unmarshal
,可以是任何 json.Unmarshal
支持的类型。
调用方式如下:
var indexes []Index
err := read(path + "/" + element + ".json", &indexes)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
英文:
Declare the function like this:
func read(filePath string, structure interface{}) error {
raw, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
return json.Unmarshal(raw, structure)
}
The structure
value is passed through to json.Unmarshal
and can be any type supported by json.Unmarshal
.
Call it like this:
var indexes []Index
err := read(path + "/" + element + ".json", &indexes)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论