打印 *string 的内容

huangapple go评论85阅读模式
英文:

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 &lt;nil&gt; 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 &quot;log&quot;

func safeDeref[T any](p *T) T {
	if p == nil {
		var v T
		return v
	}
	return *p
}

func main() {
	s := &quot;hello&quot;
	sp := &amp;s
	var np *string

	log.Printf(&quot;s: %s, sp: %s, np: %s&quot;, 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.

huangapple
  • 本文由 发表于 2022年9月6日 21:34:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/73622977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定