我正在用 Go 编写一个 Lisp 变体,并想为 Nil
和 EmptyList
定义常量。这些将在整个代码库中被引用,但我想防止它们被意外地重新定义。
// Representation of the empty list
var EmptyList = (*List)(nil)
我不能在这里使用 const
有两个原因:
const
定义不能是nil
const
定义不能是指针
我有什么选择可以确保 EmptyList
始终是 nil 指针?
最佳答案
在 Go 中,使用函数。例如,
package main
import "fmt"
type List struct{}
func IsEmptyList(list *List) bool {
// Representation of the empty list
return list == (*List)(nil)
}
func main() {
fmt.Println(IsEmptyList((*List)(nil)))
}
输出:
true
函数将被内联。
$ go tool compile -m emptylist.go
emptylist.go:7: can inline IsEmptyList
emptylist.go:13: inlining call to IsEmptyList
emptylist.go:7: IsEmptyList list does not escape
emptylist.go:13: IsEmptyList((*List)(nil)) escapes to heap
emptylist.go:13: main ... argument does not escape
$
关于go - 如何定义 `const *DataType`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33404906/