gpt4 book ai didi

function - 声明和定义中不同的函数参数类型

转载 作者:IT王子 更新时间:2023-10-29 01:34:59 24 4
gpt4 key购买 nike

在标准库中,src/time/sleep.go有以下内容:

// Interface to timers implemented in package runtime.
// Must be in sync with ../runtime/runtime.h:/^struct.Timer$
type runtimeTimer struct {
i int
when int64
period int64
f func(interface{}, uintptr) // NOTE: must not be closure
arg interface{}
seq uintptr
}

func startTimer(*runtimeTimer)

startTimer的参数类型为*runtimeTimerstartTimer的实现在src/runtime/time.go中,如下:

// Package time knows the layout of this structure.
// If this struct changes, adjust ../time/sleep.go:/runtimeTimer.
// For GOOS=nacl, package syscall knows the layout of this structure.
// If this struct changes, adjust ../syscall/net_nacl.go:/runtimeTimer.
type timer struct {
i int // heap index

// Timer wakes up at when, and then at when+period, ... (period > 0 only)
// each time calling f(arg, now) in the timer goroutine, so f must be
// a well-behaved function and not block.
when int64
period int64
f func(interface{}, uintptr)
arg interface{}
seq uintptr
}

// startTimer adds t to the timer heap.
//go:linkname startTimer time.startTimer
func startTimer(t *timer) {
if raceenabled {
racerelease(unsafe.Pointer(t))
}
addtimer(t)
}

这里startTimer的参数类型是*timer

*timer*runtimeTimer 是不同的类型。因为根据 golang spec :

Two pointer types are identical if they have identical base types

A defined type is always different from any other type

timerruntimeTimer 都是定义类型,所以*timer*runtimeTimer 是不同的类型。

根据可分配性rule ,函数调用中的参数赋值也不应该起作用。

有人能给我解释一下吗?

谢谢

最佳答案

runtime package function is :

//go:linkname startTimer time.startTimer
func startTimer(t *timer) {
if raceenabled {
racerelease(unsafe.Pointer(t))
}
addtimer(t)
}

//go:linkname 注释是 compiler directive :

//go:linkname localname importpath.name

The //go:linkname directive instructs the compiler to use “importpath.name” as the object file symbol name for the variable or function declared as “localname” in the source code. Because this directive can subvert the type system and package modularity, it is only enabled in files that have imported "unsafe".

此指令告诉编译器使用 time.startTimer 作为此函数的目标文件符号。

time package function只是一个声明。在链接时,time.startTimer 名称绑定(bind)到运行时包中实现的函数。这种名称匹配忽略了类型安全和模块化。

这些恶作剧的目的是允许时间包调用运行时包函数,而无需从运行时包中导出该函数。

关于function - 声明和定义中不同的函数参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48456128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com