Rumah > Artikel > pembangunan bahagian belakang > Skop Medan Struktur Golang
Dalam bahasa lain, ini akan serupa dengan kelayakan akses awam.
Jika medan (iaitu atribut) struct bermula dengan huruf besar, ini bermakna medan itu dieksport, dengan itu boleh diakses di luar pakej.
Anggapkan kami mempunyai fail berikut dalam projek Go:
main.go /library /book.go
Kami akan mentakrifkan book.go dalam pakejnya sendiri.
// 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 }
Apabila menggunakannya dalam 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) }
Dalam Ruby, ini adalah sinonim dengan menggunakan attr_accessor kerana kita boleh:
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
Ini serupa dengan kelayakan akses peribadi dalam bahasa lain
Jika ia bermula dengan huruf kecil, medan tidak akan dapat diakses.
Cuba sendiri!
Andaikan nama modul anda ialah myapp dalam go.mod
// go.mod module myapp go 1.22.5
Kami mencipta fail baharu dalam library/book.go di bawah pustaka pakej
// 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 }
Import pakej ke 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) }
Jika anda mempunyai persediaan Go dalam VSCode, anda akan mendapat ralat lint berikut pada talian:
unknown field author in struct literal of type library.Bookcompiler[MissingLitField](https://pkg.go.dev/golang.org/x/tools/internal/typesinternal#MissingLitField
Atas ialah kandungan terperinci Skop Medan Struktur Golang. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!