这里是否生成了某种构造函数?

Geo*_*Geo 0 sorting go

在其中一个排序示例中,它们使用以下代码:

package main

import (
    "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 []Person

func (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)

}
Run Code Online (Sandbox Code Playgroud)

排序的行对我来说有点混乱:

sort.Sort(ByAge(people))
Run Code Online (Sandbox Code Playgroud)

ByAge(人)是否会生成某种复制传入数组的构造函数?我不确定我是否理解新类型ByAge如何能够访问这些元素.

fuz*_*fuz 5

语法foo(expr)where foo是一种类型,expr是一种类型转换,规范中所述:

转换

转换是表单的表达式,T(x)其中T是一个类型,x 是一个可以转换为类型的表达式T.

Conversion = Type "(" Expression [ "," ] ")" .

如果类型与操作者启动*<-,或者如果类型以关键字开头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)
Run Code Online (Sandbox Code Playgroud)

在任何这些情况下,常量值x都可以转换为类型T:

  • x可由类型值表示T.
  • x是一个浮点常量,T是浮点类型,并且在使用IEEE 754舍入到偶数规则进行舍入后可以通过x类型值表示T.常量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
Run Code Online (Sandbox Code Playgroud)

在任何这些情况下,非常数值x都可以转换为类型T:

  • x可分配给T.
  • x的类型和T底层类型相同.
  • x的类型和T是未命名的指针类型,它们的指针基类型具有相同的基础类型.
  • x的类型,T都是整数或浮点类型.x的类型,T都是复杂的类型.
  • x是一个整数或一个字节或符文切片,T是一个字符串类型.
  • x是一个字符串,T是一个字节或符文的片段.

特定规则适用于数字类型之间或字符串类型之间的(非常量)转换.这些转换可能会改变x运行时成本并导致运行时成本.所有其他转换仅更改类型,但不更改表示x.

没有语言机制来在指针和整数之间进行转换.软件包unsafe在受限情况下实现此功能.

有关详细信息,请参阅链接页面.