go - 如何定义 `const *DataType`

标签 go

我正在用 Go 编写一个 Lisp 变体,并想为 NilEmptyList 定义常量。这些将在整个代码库中被引用,但我想防止它们被意外地重新定义。

// Representation of the empty list
var EmptyList = (*List)(nil)

我不能在这里使用 const 有两个原因:

  1. const 定义不能是nil
  2. 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/

相关文章:

security - 如何防止来自用 Go 编写的 HTTP 服务器的 DDoS 攻击?

http - 通过HTTP发送文件而没有实际创建任何文件

go - 使用反射,如何设置结构字段的值?

go - sync.Once.Do 是否保证跨 goroutine 的可见性?

go - 如何从接口(interface)获取 chan 值并在 reflect.Select(...) 中使用它

http - 我无法将 header 添加到 golang 中的特定多部分

go - 使用 Golang 减少访问 Bigtable 的时间

golang, combine 2 方法内容相同

oop - 为什么go语言的方法有奇怪的语法

go - 关于 "Equivalent Binary Tree"问题