」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Go 語言結構

Go 語言結構

發佈於2024-11-08
瀏覽:218

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 類型

複合文字

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

  • 結構體
  • 陣列
  • 切片
  • 地圖

這裡我們將一個新的 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 結構類型
- book:用於存取函數內結構的變數
- Book:結構的類型
ToString() 函數名稱
細繩 函數的回傳型別
版本聲明 本文轉載於:https://dev.to/nerdherd/golang-structs-3o0k?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3