在其他语言中,这类似于公共访问限定符。
如果结构体的字段(即属性)以大写开头,则意味着该字段已导出,因此可以在包外部访问。
假设Go项目中有以下文件:
main.go /library /book.go
我们将在它自己的包中定义 book.go。
// library/book.go // Assume we have a package called "library" which contains a book. package library // Struct that represents a physical book in a library with exported fields type Book struct { Title string, Author string }
在main.go中使用时:
package main import ( "fmt" "library" // importing the package that the struct Book is in ) func main() { book := library.Book{ Title: "Book Title", Author: "John Snow" } // Print the title and author to show that the struct Book fields are accessible outisde it's package "library" fmt.Println("Title:", book.Title) fmt.Println("Author:", book.Author) }
在 Ruby 中,这与使用 attr_accessor 是同义的,因为我们可以:
class Book # allow read and write on the attributes from outside the class attr_accessor(:title, :author) def initalize(title = nil, author = nil) @title = title @author = authoer end end # usage outside of the class book = Book.new() # assinging attributes outside of the class book.title = "Book Title" book.title = "Jon Snow" # accessing attributes outside of the class puts book.title, book.author
这类似于其他语言中的私有访问限定符
如果以小写开头,则这些字段将不可访问。
亲自尝试一下!
假设你的模块名称是 go.mod 中的 myapp
// go.mod module myapp go 1.22.5
我们在包library下的library/book.go中创建一个新文件
// library/book.go // Assume we have a package called "library" which contains a book. package library // Fields start with lowercase, fields are not exported type Book struct { title string author string }
将包导入main.go
// main.go package main import ( "fmt" // import the library package "myapp/library" ) func main() { book := library.Book{ title: "Book Title", author: "John Snow" } // Print the title and author to show that the struct Book fields are accessible outisde it's package "library" fmt.Println("title:", book.title) fmt.Println("author:", book.author) }
如果您在 VSCode 中设置了 Go,您会收到以下 lint 错误:
unknown field author in struct literal of type library.Bookcompiler[MissingLitField](https://pkg.go.dev/golang.org/x/tools/internal/typesinternal#MissingLitField
以上是Golang 结构字段范围的详细内容。更多信息请关注PHP中文网其他相关文章!