英文:
How can I define a `const *DataType`
问题
我正在使用Go语言编写一个Lisp变种,并且想要为Nil
和EmptyList
定义常量。这些常量将在整个代码库中被引用,但我希望防止它们被意外重新定义。
// 空列表的表示
var EmptyList = (*List)(nil)
在这里我不能使用const
的原因有两个:
const
定义不能是nil
const
定义不能是指针
我有哪些选项可以确保EmptyList
始终是nil
指针?
英文:
I'm writing a Lisp variant in Go and want to define constants for Nil
and EmptyList
. These will be referenced throughout the codebase, but I want to prevent them from being accidentally re-defined.
// Representation of the empty list
var EmptyList = (*List)(nil)
I can't use a const
here for two reasons:
const
definitions cannot benil
const
definitions cannot be pointers
What options do I have to ensure EmptyList
is always the nil pointer?
答案1
得分: 1
在Go语言中,可以使用函数。例如,
package main
import "fmt"
type List struct{}
func IsEmptyList(list *List) bool {
// 表示空列表
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
$
英文:
In Go, use a function. For example,
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)))
}
Output:
true
The function will be inlined.
$ 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
$
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论