> For the complete documentation index, see [llms.txt](https://denglj.gitbook.io/essential-go/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://denglj.gitbook.io/essential-go/10-structs/exported-vs-unexported-fields-private-vs-public.md).

# 可导出vs不可导出字段(公有vs私有)

结构体的字段名若为大写字母开头，则为可导出字段，否则为不可导出字段。

```go
type Account struct {
    UserID      int    // exported
    accessToken string // unexported
}
```

不可导出的字段只能被相同package内的代码访问。因此，如果您确定要从*不同的包*访问一个字段，则它的名字应该以大写字母开头。

```go
package main

import "bank"

func main() {
    var x = &bank.Account{
        UserID: 1,          // this works fine
        accessToken: "one", // this does not work, since accessToken is unexported
    }
}
```

不过，在`bank`包中，您访问`UserID`或`accessToken`都没问题。

`bank`包的实现如下：

```go
package bank

type Account struct {
	UserID      int
	accessToken string
}

func ProcessUser(u *Account) {
	// ProcessUser() can access u.accessToken because
	// it's defined in the same package
	u.accessToken = doSomething(u)
}
```
