douba2011 2015-10-29 02:23
浏览 49
已采纳

如何定义const * DataType

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:

  1. const definitions cannot be nil
  2. const definitions cannot be pointers

What options do I have to ensure EmptyList is always the nil pointer?

  • 写回答

1条回答 默认 最新

  • douaikuai2715 2015-10-29 02:37
    关注

    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
    $ 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?