英文:
Is there an idiomatic go way to print string pointer contents or nil?
问题
我有一个字符串指针,可能为空,我想要打印出字符串的内容(如果存在),或者如果指针为空的话,指示指针为空。有没有一种聪明的方法可以做到这一点,而不需要使用 if 检查或临时变量(最好是一行代码)?
目前我正在使用类似这样的代码:
if p == nil {
fmt.Print(p)
} else {
fmt.Print(*p)
}
但是当有其他格式和其他变量打印在该值之前和/或之后时,这种方法特别笨拙和冗长。
英文:
I have a string pointer that may or may not be nil, and I want to print out either the contents of the string if contents exist, or indicate that the pointer is nil if it is nil. Is there a clever way to do this that doesn't involve either an if check or a temporary variable (preferably a single line)?
Right now I'm using something like this:
if p == nil {
fmt.Print(p)
} else {
fmt.Print(*p)
}
But this is particularly awkward and verbose when there is other formatting and other variables that are intended to be printed before and/or after that value.
答案1
得分: 6
你可以这样做:
func main() {
var hello SmartString = "hello"
p := &hello
p.Print()
p = nil
p.Print()
}
type SmartString string
func (p *SmartString) Print() {
if p == nil {
fmt.Println(p)
} else {
fmt.Println(*p)
}
}
无论这是否是一个好主意,都取决于你。
你甚至可以使用String接口使其与fmt.Println
一起使用。
func main() {
var hello SmartString = "hello"
p := &hello
fmt.Println(p)
p = nil
fmt.Println(p)
}
type SmartString string
func (p *SmartString) String() string {
if p == nil {
return "<nil>"
}
return string(*p)
}
英文:
You could do something like this:
func main() {
var hello SmartString = "hello"
p := &hello
p.Print()
p = nil
p.Print()
}
type SmartString string
func (p *SmartString) Print() {
if p == nil {
fmt.Println(p)
} else {
fmt.Println(*p)
}
}
Whether it's a good idea or not is up to you.
You can even use the String interface to make it work with fmt.Println
func main() {
var hello SmartString = "hello"
p := &hello
fmt.Println(p)
p = nil
fmt.Println(p)
}
type SmartString string
func (p *SmartString) String() string {
if p == nil {
return "<nil>"
}
return string(*p)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论