首頁 > 後端開發 > Golang > 主體

Golang 結構字段範圍

王林
發布: 2024-08-31 20:30:41
原創
1178 人瀏覽過

結構字段範圍

導出字段

在其他語言中,這類似於公共存取限定符。

  • 如果你像我一樣來自 Ruby,這將使用 attr_accessor 定義屬性

如果結構體的欄位(即屬性)以大寫開頭,則表示該欄位已匯出,因此可以在套件外部存取。

假設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 錯誤:

  • 標題:「書名

Golang Struct Field Scopes

unknown field author in struct literal of type library.Bookcompiler[MissingLitField](https://pkg.go.dev/golang.org/x/tools/internal/typesinternal#MissingLitField
登入後複製

以上是Golang 結構字段範圍的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板