dony113407 2016-07-23 12:05
浏览 40
已采纳

为什么可以导出私有类型的变量

Think like this :

package first

type person struct {
    Name string
}

var Per = person{
    Name: "Jack",
}

and in main package

package main

import "first"
import "fmt"

func main(){
    o := first.Per
    fmt.Println(o)
}

the above works, as we can see that the variable in first package was visible outside but it's type was not, but it gives no error? And how it can be useful outside package?

  • 写回答

2条回答 默认 最新

  • dqwolwst50489 2016-07-23 14:15
    关注

    it is fine:

    Exported identifiers:

    An identifier may be exported to permit access to it from another package. An identifier is exported if both:

    • the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
    • the identifier is declared in the package block or it is a field name or method name. All other identifiers are not exported.

    ref: https://golang.org/ref/spec

    and even you can use Getters:

    Go doesn't provide automatic support for getters and setters. There's nothing wrong with providing getters and setters yourself, and it's often appropriate to do so, but it's neither idiomatic nor necessary to put Get into the getter's name. If you have a field called owner (lower case, unexported), the getter method should be called Owner (upper case, exported), not GetOwner. The use of upper-case names for export provides the hook to discriminate the field from the method. A setter function, if needed, will likely be called SetOwner. Both names read well in practice:

    owner := obj.Owner()
    if owner != user {
        obj.SetOwner(user)
    }  
    

    ref: https://golang.org/doc/effective_go.html

    so if you do not want to export Name make it lower case, like this working sample codes and use Getter/Setter :

    package first
    
    type person struct {
        name string
    }
    
    var Per = person{
        name: "Jack",
    }
    
    func (p *person) SetName(name string) {
        p.name = name
    }
    
    func (p *person) Name() string {
        return p.name
    }
    

    main.go (with commented output):

    package main
    
    import "first"
    import "fmt"
    
    func main() {
        person := first.Per
        fmt.Println(person.Name()) //Jack
        person.SetName("Alex")
        fmt.Println(person.Name()) //Alex
    }
    

    another use cases:

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

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊