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

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

這里是否生成了某種構造函數?

這里是否生成了某種構造函數?

Go
素胚勾勒不出你 2021-09-09 21:46:49
在排序示例之一中,他們使用以下代碼:package mainimport (    "fmt"    "sort")type Person struct {    Name string    Age  int}func (p Person) String() string {    return fmt.Sprintf("%s: %d", p.Name, p.Age)}// ByAge implements sort.Interface for []Person based on// the Age field.type ByAge []Personfunc (a ByAge) Len() int           { return len(a) }func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }func main() {    people := []Person{        {"Bob", 31},        {"John", 42},        {"Michael", 17},        {"Jenny", 26},    }    fmt.Println(people)    sort.Sort(ByAge(people))    fmt.Println(people)}帶有 Sort 的那一行對我來說有點混亂:sort.Sort(ByAge(people))ByAge(people) 是否生成某種構造函數來復制傳入的數組?我不確定我是否理解新類型 ByAge 如何以其他方式訪問元素。
查看完整描述

1 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

語法foo(expr)where foois a type and expris a type conversion,如規范中所述:


轉化次數

轉換是形式為T(x)where Tis a type and x is an expression that can convert to type 的表達式T。


轉換 = 類型 "(" 表達式 [ "," ] ")" 。

如果類型以運算符*or開頭<-,或者類型以關鍵字開頭func且沒有結果列表,則必須在必要時將其括起來以避免歧義:


*Point(p)        // same as *(Point(p))

(*Point)(p)      // p is converted to *Point

<-chan int(c)    // same as <-(chan int(c))

(<-chan int)(c)  // c is converted to <-chan int

func()(x)        // function signature func() x

(func())(x)      // x is converted to func()

(func() int)(x)  // x is converted to func() int

func() int(x)    // x is converted to func() int (unambiguous)

在以下任何一種情況下,常量值x都可以轉換為類型T:


x可以用一個類型的值來表示T。

x是浮點常量,T是浮點類型,并且x可以T使用 IEEE 754 舍入到偶數規則舍入后由 type 的值表示。常數T(x)是四舍五入的值。

x是整數常量,T是字符串類型。x在這種情況下適用與非常量相同的規則。

轉換一個常量會產生一個類型化的常量作為結果。


uint(iota)               // iota value of type uint

float32(2.718281828)     // 2.718281828 of type float32

complex128(1)            // 1.0 + 0.0i of type complex128

float32(0.49999999)      // 0.5 of type float32

string('x')              // "x" of type string

string(0x266c)           // "?" of type string

MyString("foo" + "bar")  // "foobar" of type MyString

string([]byte{'a'})      // not a constant: []byte{'a'} is not a constant

(*int)(nil)              // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type

int(1.2)                 // illegal: 1.2 cannot be represented as an int

string(65.0)             // illegal: 65.0 is not an integer constant

在以下任何一種情況下,非常量值 x 都可以轉換為類型 T:


x可分配給T。

x的類型并T具有相同的基礎類型。

x的類型并且T是未命名的指針類型,并且它們的指針基類型具有相同的底層類型。

x的類型并且T都是整數或浮點類型。x的類型 和T都是復雜類型。

x是一個整數或一個字節片或符文,并且T是一個字符串類型。

x是一個字符串,T是一個字節或符文的切片。

特定規則適用于數字類型之間或與字符串類型之間的(非常量)轉換。這些轉換可能會改變表示x并產生運行時成本。所有其他轉換僅更改類型,而不更改x.


沒有在指針和整數之間轉換的語言機制。包 unsafe 在受限情況下實現此功能。


有關更多詳細信息,請參閱鏈接頁面。


查看完整回答
反對 回復 2021-09-09
  • 1 回答
  • 0 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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