variables - 为什么可以导出私有(private)类型的变量

标签 variables go types scope

这样想:

package first

type person struct {
    Name string
}

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

在主包中

package main

import "first"
import "fmt"

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

上面的工作,因为我们可以看到第一个包中的变量在外面是可见的,但它的类型不是,但它没有给出错误?以及它如何在外包装中发挥作用?

最佳答案

没关系:

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.

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

甚至你可以使用 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)
}  

引用:https://golang.org/doc/effective_go.html

所以如果你不想导出 Name 让它小写,就像这个工作示例代码并使用 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(带有注释输出):

package main

import "first"
import "fmt"

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

另一个用例:

关于variables - 为什么可以导出私有(private)类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38541598/

相关文章:

python - 如何为队列中的内容添加变量类型注释?

typescript - 有没有办法获取 interface[key] 为类型的接口(interface)的键?

c++ - 使部分代码中的变量不可用

go - 如何在 Go 中模拟 Stripe?

c - int 指针类型为 int

走 - 时间 - 毫秒

queue - 是否可以将 Go 的缓冲 channel 用作线程安全队列?

php - 在 echo 语句中添加 PHP 变量作为 href 链接地址?

typescript - var$后面的$是什么意思?

perl - Perl中double 'at'(@@)是什么意思?