【问题标题】:How to convert a 'string pointer' to a string in Golang?如何将“字符串指针”转换为 Golang 中的字符串?
【发布时间】:2014-12-17 02:30:15
【问题描述】:

是否可以从指向字符串的指针中获取字符串值?

我正在使用goopt package 处理标志解析,并且包仅返回 *string。我想使用这些值来调用地图中的函数。

Example

var strPointer = new(string)
*strPointer = "string"

functions := map[string]func() {
    "string": func(){
        fmt.Println("works")
    },
}  

//Do something to get the string value

functions[strPointerValue]()

返回

./prog.go:17:14: cannot use strPointer (type *string) 
as type string in map index

【问题讨论】:

    标签: string pointers go type-conversion


    【解决方案1】:

    首先检查字符串指针是否为 nil 的简单函数可以防止运行时错误:

    func DerefString(s *string) string {
        if s != nil {
            return *s
        }
    
        return ""
    }
    
    

    【讨论】:

    • 比接受的答案更好,因为它表明程序员必须记住指针为零的可能性
    【解决方案2】:

    取消引用指针:

    strPointerValue := *strPointer
    

    【讨论】:

    • 没错,但如果指针字符串为nil,则会出现运行时错误
    • 那么更好的解决方案是什么?
    • @ram4nd if strPointer != nil { strPointerValue := *strPointer }
    猜你喜欢
    • 2013-03-06
    • 1970-01-01
    • 2011-12-12
    • 2019-05-09
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多