Skip to content

Latest commit

 

History

History
101 lines (71 loc) · 2.55 KB

File metadata and controls

101 lines (71 loc) · 2.55 KB

33) Exported Fields

Linkedin Follow X Follow
Interactive Learning


Exported Fields

In Go, the first letter of a name controls its visibility.

There are no public or private keywords.

Exported vs Unexported

↳ 1) Exported — starts with an uppercase letter

Accessible from other packages.

type User struct {
    Name  string  // exported
    Email string  // exported
}

↳ 2) Unexported — starts with a lowercase letter

Only accessible within the same package.

type User struct {
    Name     string  // exported
    password string  // unexported
}

Same Rule for Methods

Methods follow the same rule:

func (u User) GetName() string { ... }  // exported
func (u User) validate() bool { ... }   // unexported

Why It Matters

When you import a struct from another package, you can only access exported fields and methods.

This is how Go controls visibility across packages.

Since all exercises in this guide are single-file package main programs, both exported and unexported fields work within the same file. The distinction matters when code spans multiple packages.

Example Code

There are some exported and unexported fields in main.go file.

But they are incomplete.

Fix the Code

Open main.go file and complete the code lines.

Then validate your code by running:

go run topic.go 33 validate

✅ If everything is ok, you should see:

OK!

Conclusion

Now you know how exported fields work in Go.

Continue to the next topic 👇

Project ⮕️