gpt4 book ai didi

Go:通过接口(interface)访问结构体的属性{}

转载 作者:行者123 更新时间:2023-12-03 01:29:39 24 4
gpt4 key购买 nike

我在访问不同文件中的一个结构的属性(名为 Params)时遇到问题。

请考虑我调用函数(CreateTodo)的 x.go

type Params struct {
Title string `json:"title"`
IsCompleted int `json:is_completed`
Status string `json:status`
}

var data = &Params{Title:"booking hotel", IsCompleted :0,Status:"not started"}

isCreated := todoModel.CreateTodo(data) // assume todoModel is imported

现在 CreateTodo 是不同文件中的结构(名为 Todo)的方法,比如 y.go

type Todo struct {
Id int `json:todo_id`
Title string `json:"title"`
IsCompleted int `json:is_completed`
Status string `json:status`
}

func (mytodo Todo)CreateTodo(data interface{}) bool{
// want to access the properties of data here
fmt.Println(data.Title)
return true
}

现在我只想使用 y.go 中 CreateTodo 函数中的数据属性。但我无法这样做并收到以下错误

data.Title undefined (type interface {} is interface with no methods)

我确信问题在于接受结构作为空接口(interface),但我无法弄清楚。

请帮忙。谢谢

最佳答案

因此,您有两个选择之一,具体取决于您的型号:

#1

按照另一个答案中的建议,切换到 data *Params 而不是 data interface{} 但看起来您希望在此函数中使用不同的类型,如果是这样;检查下面的选项#2。

#2

使用Type switches如下:

func (t Todo) CreateTodo(data interface{}) bool {
switch x := data.(type) {
case Params:
fmt.Println(x.Title)
return true

// Other expected types

default:
// Unexpected type
return false
}
}
<小时/>

附注请小心您的 json 标签:它应该是 json:"tagName"。注意""!检查go vet .

关于Go:通过接口(interface)访问结构体的属性{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58537440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com