Golang中如何打印结构体的字段 %+v

Golang中如何打印结构体的字段 %+v 如何打印结构体的字段名称(这里的 t 和 p)?

package main

import "fmt"

type drive interface {
	carry() string
}

type vehicle struct{
	passengers, cargo bool
}

func (t vehicle) carry() string{
	if t.cargo && t.passengers {
		return "Yes it is truck"
	}
	return "No it is not a truck"
}
// How to print the "t" and "p"?
func categorized_result(d drive){
	fmt.Println("%v\n", d)
	fmt.Println(d.carry())
}

func main(){
	fmt.Println("Hello World")
	fmt.Println("Main function starts here!")
	t := vehicle {cargo: true, passengers: true}
	p := vehicle {cargo: false, passengers: true}
	categorized_result(t)
	categorized_result(p)
}
/*
Need Output Like this:
----------------------
Hello World
Main function starts here!
T:  Yes it is truck
P:  No it is not a truck
*/

更多关于Golang中如何打印结构体的字段 %+v的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

传递的变量名:

https://play.golang.org/p/KakDr--iXX2

更多关于Golang中如何打印结构体的字段 %+v的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在你的示例中,"t"和"p"并不是任何结构体的字段,它们与你想要打印的"T"或"P"并不相同。

为什么不直接打印你需要的内容呢?

// 代码示例应保持原样

在Go语言中,要打印结构体的字段名称和值,可以使用%+v格式化动词。但在你的代码中,需要修改categorized_result函数来区分不同的变量并打印字段值。

以下是修改后的代码:

package main

import "fmt"

type drive interface {
	carry() string
}

type vehicle struct {
	passengers, cargo bool
}

func (t vehicle) carry() string {
	if t.cargo && t.passengers {
		return "Yes it is truck"
	}
	return "No it is not a truck"
}

func categorized_result(name string, d drive) {
	fmt.Printf("%s: %+v\n", name, d)
	fmt.Printf("%s: %s\n", name, d.carry())
}

func main() {
	fmt.Println("Hello World")
	fmt.Println("Main function starts here!")
	t := vehicle{cargo: true, passengers: true}
	p := vehicle{cargo: false, passengers: true}
	
	categorized_result("T", t)
	categorized_result("P", p)
}

输出结果:

Hello World
Main function starts here!
T: {passengers:true cargo:true}
T: Yes it is truck
P: {passengers:true cargo:false}
P: No it is not a truck

关键修改点:

  1. categorized_result函数中添加了name参数来标识变量名
  2. 使用fmt.Printf%+v格式化动词来打印结构体的字段名和值
  3. 使用%s格式化字符串来显示变量名和对应的结果

%+v格式化动词会打印结构体的字段名称和对应的值,这正是你需要的功能。

回到顶部