登录
首页 >  Golang >  Go问答

使用接口访问结构体属性的方法{}

来源:stackoverflow

时间:2024-03-06 12:57:28 369浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《使用接口访问结构体属性的方法{}》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

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

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

type params struct {
    title  string `json:"title"`
    iscompleted int `json:is_completed`
    status  string `json:status`
}

var data = ¶ms{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)

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

请帮忙。谢谢


解决方案


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

#1

按照另一个答案中的建议,切换到 data *params 而不是 data 接口{},但看起来您希望在此函数中使用不同的类型,如果是这样;检查下面的选项#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

以上就是《使用接口访问结构体属性的方法{}》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>