drmeu26880 2016-02-16 22:34
浏览 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 22: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条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?