Go(golang)- do方法指针在每个源代码定义中总是递增吗?

huangapple go评论113阅读模式
英文:

Go (golang) - do method pointers always increment per source definition?

问题

在Go语言中定义方法时,指针的增量顺序是否总是与它们在源代码中定义的顺序完全一致,或者可能会重新分配较低的指针空间?

例如,不论Go版本或架构,methods是否保证按照A、Z、D、B的顺序排列?

package main

import (
    "fmt"
    "reflect"
    "sort"
)

type t struct{}

func (a *t) A() {}
func (a *t) Z() {}
func (a *t) D() {}
func (a *t) B() {}

type addr struct {
    Addr   uintptr
    Method string
}

type addrList []addr

func (a addrList) Len() int {
    return len(a)
}

func (a addrList) Less(i, j int) bool {
    return a[i].Addr < a[j].Addr
}

func (a addrList) Swap(i, j int) {
    a[i], a[j] = a[j], a[i]
}

func main() {

    methods := addrList{}
    fooType := reflect.TypeOf(&t{})

    for i := 0; i < fooType.NumMethod(); i++ {
        method := fooType.Method(i)
        methods = append(methods, addr{method.Func.Pointer(), method.Name})
    }

    sort.Sort(methods)
    fmt.Println(methods)
}
英文:

When methods are defined in Go, does the pointer always increment in the exact order in which they are defined in source - or is it possible that lower pointer space could be re-allocated?

For example - is methods now in the guaranteed order of A, Z, D, B regardless of go version or arch?

package main

import (
    &quot;fmt&quot;
    &quot;reflect&quot;
    &quot;sort&quot;
)

type t struct{}

func (a *t) A() {}
func (a *t) Z() {}
func (a *t) D() {}
func (a *t) B() {}

type addr struct {
    Addr   uintptr
    Method string
}

type addrList []addr

func (a addrList) Len() int {
    return len(a)
}

func (a addrList) Less(i, j int) bool {
    return a[i].Addr &lt; a[j].Addr
}
func (a addrList) Swap(i, j int) {
    a[i], a[j] = a[j], a[i]
}

func main() {

    methods := addrList{}
    fooType := reflect.TypeOf(&amp;t{})

    for i := 0; i &lt; fooType.NumMethod(); i++ {
        method := fooType.Method(i)
        methods = append(methods, addr{method.Func.Pointer(), method.Name})
    }

    sort.Sort(methods)
    fmt.Println(methods)
}

答案1

得分: 4

《Go编程语言规范》

这是Go编程语言的参考手册。

在Go语言规范中,顺序没有定义,因此顺序是未定义的。它取决于具体的实现。

英文:

> The Go Programming Language Specification
>
> This is a reference manual for the Go programming language.

The order is not defined in the Go language specification therefore the order is undefined. It's implementation dependent.

huangapple
  • 本文由 发表于 2016年1月3日 21:15:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/34576919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定