亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

main 函數是否運行一個 goroutine?

main 函數是否運行一個 goroutine?

Go
翻過高山走不出你 2023-05-08 18:01:33
為什么我們要在結構的類型定義之外聲明方法?例如:type antenna struct {    name string    length float32    girth float32    bloodtype string}func (p *antenna) extend() {    p.length += 10}在我看來,該方法可能是結構的一部分?(讓我們暫時忽略結構應該是值類型)type antenna struct {    name string    length float32    girth float32    bloodtype string    func extend() {        length += 10    }}這將更類似于傳統的 OOP。除了“結構是值類型而類是引用類型”之外,我沒有找到任何很好的解釋為什么它是這樣完成的。我知道其中的區別,但這對我來說不是一個令人滿意的答案。無論如何都必須像這樣調用該方法:var x = antenna()x.extend() 那么將結構和方法分開有什么意義呢?讓它們在代碼中直觀地組合在一起——就像在典型的 OOP 語言中一樣——對我來說似乎有用嗎?
查看完整描述

1 回答

?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

TLR:代碼重用一致性。

1 - 這可以重用方法
這是 Go 中類型的關鍵設計原則interface- 讓我用一個例子更清楚地說明:考慮你需要對一片進行排序(在這里int嘗試):

? a := []int{1, 3, 2, 5, 4}

? ? sort.Ints(a)? ?// sort.Sort(sort.IntSlice(a))

? ? fmt.Println(a) // [1 2 3 4 5]

您只需調用sort.Ints(a)which 然后Sort(IntSlice(a))在標準庫中調用:


type IntSlice []int


func (x IntSlice) Len() int? ? ? ? ? ?{ return len(x) }

func (x IntSlice) Less(i, j int) bool { return x[i] < x[j] }

func (x IntSlice) Swap(i, j int)? ? ? { x[i], x[j] = x[j], x[i] }

sort.IntSlice sort.Interface將: Len、Less和的 3 種方法附加Swap到類型[]int, 以調用:


// Sort sorts data in ascending order as determined by the Less method.

// It makes one call to data.Len to determine n and O(n*log(n)) calls to

// data.Less and data.Swap. The sort is not guaranteed to be stable.

func Sort(data Interface) {

? ? n := data.Len()

? ? quickSort(data, 0, n, maxDepth(n))

}

因此,您可以重用標準庫中的方法,而無需再次重新實現它。


2-您可以定義自己的類型,請參見此示例-此命名類型在此處沒有內部-因此方法必須在該類型之外:


package main


import "fmt"


type num int32


func (p *num) inc() {

? ? *p++

}


func main() {

? ? p := num(100)

? ? p.inc()

? ? fmt.Println(p) // 101

}

上面命名的類型 num與這個用戶定義的類型:通過設計,這使得兩種類型的Go 語言保持一致:



type Animal struct {

? ? Name? string

? ? moves []move.Direction

}


func (p *Animal) Walk(dir move.Direction) {

? ? p.moves = append(p.moves, dir)

}


查看完整回答
反對 回復 2023-05-08
  • 1 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號