sách gpt4 ăn đã đi

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

In lại 作者:IT王子 更新时间:2023-10-29 01:54:50 27 4
mua khóa gpt4 giày nike

这样想:

package first

type person struct {
Chuỗi tên
}

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

在主包中

gói chính

import "first"
nhập khẩu "fmt"

hàm main(){
o := first.Per
fmt.Println(o)
}

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

câu trả lời hay nhất

没关系:

Exported identifiers:

Một định danh có thể được xuất để cho phép truy cập vào nó từ một gói khác. Một định danh được xuất nếu cả hai:

  • 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.

Trích dẫn: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)
}

Trích dẫn:https://golang.org/doc/effective_go.html

所以如果你不想导出 Tên 让它小写,就像这个工作示例代码并使用 Getter/Setter :

package first

type person struct {
chuỗi tên
}

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

func (p *person) SetName(name string) {
p.name = name
}

func (p *person) Name() string {
return p.name
}

main.go(带有注释输出):

gói chính

import "first"
nhập khẩu "fmt"

hàm 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/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress