下面的代码能不能编译通过,如果能,输出什么?
package main
func add(old, new int) int{
return old + new
}
func main() {
println(add(1,2))
}
我们都知道new是Go的内置函数用于创建指针,但编译器并没有强行限制不能用new做变量名。运行上面的代码可以得到输出:
3
事实上在Go的源代码中大量使用new来做变量名,例如:
./strings/strings.go:928:func Replace(s, old, new string, n int) string {
./strings/strings.go:967:func ReplaceAll(s, old, new string) string {
./runtime/internal/atomic/stubs.go:12:func Cas(ptr *uint32, old, new uint32) bool
./runtime/internal/atomic/stubs.go:15:func Casp1(ptr *unsafe.Pointer, old, new unsafe.Pointer) bool
./runtime/internal/atomic/stubs.go:18:func Casuintptr(ptr *uintptr, old, new uintptr) bool
./runtime/runtime2.go:257:func (gp *guintptr) cas(old, new guintptr) bool {
./runtime/atomic_pointer.go:72:func sync_atomic_CompareAndSwapPointer(ptr *unsafe.Pointer, old, new unsafe.Pointer) bool {
./runtime/profbuf.go:125:func (x *profAtomic) cas(old, new profIndex) bool {