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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26493923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:17:49  来源:igfitidea点击:

How to convert a 'string pointer' to a string in Golang?

stringpointersgotype-conversion

提问by Jared Meyering

Is it possible to get the string value from a pointer to a string?

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

I am using the goopt packageto handle flag parsing and the package returns *string only. I want to use these values to call a function in a map.

我正在使用goopt 包来处理标志解析,并且该包仅返回 *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]()

returns

返回

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

回答by OneOfOne

Dereference the pointer:

取消引用指针:

strPointerValue := *strPointer