gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:54:50 26 4
gpt4 key购买 nike

这样想:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com