drmeu26880 2016-02-16 14:34 采纳率: 0%
浏览 124
已采纳

如何从Golang中的结构访问特定字段

Suppose I have the following code:

type User struct {
    ID              string
    Username        string
    Name            string
    Password        string
}

What I want to do is create another struct that can access certain fields from the User struct, instead of accessing all of it, to prevent people from seeing the password, for example. This does not work:

type Note struct {
    ID         string
    Text       string
    UserID     User.ID          
}

Is there any way to do this, or do I simply create the Note.UserID field to have the same data type as the ID in the User struct?

  • 写回答

2条回答 默认 最新

  • draxu26480 2016-02-16 14:57
    关注

    Assuming the types are in different packages you can do this by exporting vs not exporting the fields. A field who's name begins with a lower case letter is not exported, meaning it is not visible outside the package where it is declared/defined. So, in this case if the user existed in one package, call it user while the other type were declared in another you could accomplish this 'hiding' of properties by changing the definition to;

    type User struct {
        ID              string
        username        string
        name            string
        password        string
    }
    

    If the two types live in the same package there is no way of making a field private/hidden/ect, everything will be available in that scope.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部