如何将“字符串指针”转换为 Golang 中的字符串?

Posted

技术标签:

【中文标题】如何将“字符串指针”转换为 Golang 中的字符串?【英文标题】:How to convert a 'string pointer' to a string in 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

【问题讨论】:

【参考方案1】:

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

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

    return ""


【讨论】:

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

取消引用指针:

strPointerValue := *strPointer

【讨论】:

没错,但如果指针字符串为nil,则会出现运行时错误 那么更好的解决方案是什么? @ram4nd if strPointer != nil strPointerValue := *strPointer

以上是关于如何将“字符串指针”转换为 Golang 中的字符串?的主要内容,如果未能解决你的问题,请参考以下文章

如何将 const 字符串引用与字符串指针进行比较?

c语言中,如何将字符串数组中的52提取出来,并转换为int类型

使用c++的windows编程中一个string对象内容为"默认字符串",如何转换为TCHAR数组

golang 将字符串转换为字节

go语言之字符串指针数组切片

golang 将任何Go接口{}转换为字符串