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

Go 語言結構

WBOY
發布: 2024-08-30 06:41:06
原創
488 人瀏覽過

GoLang Structs

在 Golang 中,結構體是簡單的資料容器。

  • 可以有欄位
  • 沒有附加任何方法
    • 單獨定義並與結構類型關聯的方法。

下面顯示了 Ruby 和 GoLang 中的一個簡單的 Book 類別等效項。

class Book
  attr_reader(:title, :author)

  def initalize(title, author)
    @title  = title
    @author = authoer
  end
end

# usage
book = Book.new('Title', 'Jon Snow')
登入後複製
// Equivalent to `class Book` in ruby
type Book struct {
  Title string,
  Author string
}
登入後複製

實例化 GoLang 類型

複合文字

複合文字是一步建立初始化複合型別的語法。我們可以實例化以下類型:

  • 結構
  • 數組
  • 切片
  • 地圖

這裡我們將一個新的 Book 實例指派給變數 book

// Composite Literal
book := Book{
  Title: "Title",
  Author: "Author"
}
登入後複製

使用新關鍵字

較長的形式是使用 new 關鍵字。這類似於我們在 Ruby 中使用 book = Book.new(..)

實例化一個類別的方式

我們將使用 = 符號來分配書籍的屬性(即標題和作者)。

// Using the `new` keyword
book        := new(Book)
book.Title  = "Book Title"
book.Author = "John Snow"
登入後複製

沒有短變數宣告 (:=)

注意到我們在第一個範例中使用了符號 := 嗎?

它是以下宣告變數並為其賦值的詳細方式的語法糖。

// Without Short Virable Declaration

// Example 1
var book Book // Declare variable `book` of type `Book`
book.Title = "Book Title" // Assign the value to book variable
book.Author = "John Snow"

// Example 2
var count int
count = 20
登入後複製

工廠功能

當我們需要時,我們也可以使用工廠模式來簡化結構體的初始化:

  • 增加額外邏輯
  • 新增預設值

假設我們希望將書名和作者標記的每個第一個字元大寫。

// Factory Function
func NewBook(title string, author string) Book {
  return Book{
    Title: titlelise(title), // default logic to "titlelise" 
    Author: titlelist(author)
  }
}

func titlelise(str string) {
  caser := cases.Title(lanaguage.English)
  return caser.String(str)
}
登入後複製

將函數附加到結構體

在 Ruby 中,我們只需在類別中定義一個函數即可。在這裡,我們定義一個名為 to_string() 的函數來列印書名作者。

class Book
  attr_reader(:title, :author)

  def initalize(title, author)
    @title  = title
    @author = authoer
  end

  # new function we added
  def to_string()
    put "#{title} by #{string}"
  end
end
登入後複製

在 GoLang 中,我們透過將結構傳遞給函數來「附加」函數。

// Equivalent to `class Book` in ruby
type Book struct {
  Title string,
  Author string
}

// Attaching the function to the `struct`
func (book Book) ToString() string {
  return fmt.Sprintf("%s by %s", book.Title, book.Author)
}

// Usage
book := Book{
  Title: "Title",
  Author: "Author"
}

book.ToString()
// => Title by Author
登入後複製

解釋:

func (book Book) ToString() string
登入後複製
令牌 描述 標題> 函數 函數關鍵字 (書本) 將函數附加到 Book 結構類型
Token Description
func function keyword
(book Book) Attaching the function to the type Book struct
- book: variable to access the struct within the function
- Book: type of the struct
ToString() name of the function
string return type of the function
- book:用於存取函數內結構的變數- Book:結構的類型 ToString() 函數名稱 字串 函數的回傳類型 表>

以上是Go 語言結構的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!