英文:
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 (
"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)
}
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论