在其他語言中,這類似於公共存取限定符。
如果結構體的欄位(即屬性)以大寫開頭,則表示該欄位已匯出,因此可以在套件外部存取。
假設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中文網其他相關文章!