英文:
Print the Content of *string
问题
fmt.Printf
系列中有很多动词,但是通过文档(https://pkg.go.dev/fmt)我找不到一种简单的方法来打印*string
及其类似类型的内容(如果是nil
指针,则打印<nil>
)。我希望%v
可以实现这个目的,但它返回的是指针的地址。
我是否漏掉了什么,还是每次我想将这种指针值的内容写入错误消息或日志条目时都必须使用实用方法?
英文:
There are so many verbs for the fmt.Printf
family, but going through the documentation (https://pkg.go.dev/fmt) I can't find an easy way to print the content of a *string
and alike (with something like <nil>
in case it's a nil
pointer). I was hoping that %v
might serve that purpose, but that returns the pointer's address instead.
Am I missing something here or do I have to resort to utility methods everytime I want to write the content of such a pointer value into an error message or a log entry?
答案1
得分: 0
虽然不如动词方便,但这是一个适用于任何指针类型的实用函数:
package main
import "log"
func safeDeref[T any](p *T) T {
if p == nil {
var v T
return v
}
return *p
}
func main() {
s := "hello"
sp := &s
var np *string
log.Printf("s: %s, sp: %s, np: %s", s, safeDeref(sp), safeDeref(np))
}
2022/09/06 15:01:50 s: hello, sp: hello, np:
在惯用的 Go 语言中,*string
是相当罕见的。除非你真的需要 nil
,我建议只使用 string
。
英文:
While not as convenient as a verb, here's one utility function will work for any pointer type:
package main
import "log"
func safeDeref[T any](p *T) T {
if p == nil {
var v T
return v
}
return *p
}
func main() {
s := "hello"
sp := &s
var np *string
log.Printf("s: %s, sp: %s, np: %s", s, safeDeref(sp), safeDeref(np))
}
2022/09/06 15:01:50 s: hello, sp: hello, np:
*string
is pretty rare in idiomatic Go. Unless you really need nil
, I'd suggest just using string
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论