如何在golang中逐个打印数组的结果?

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

How to print the result one by one from an array in golang?

问题

在这段代码中,我正在根据电子邮件和密码查找数据。但是我想做另一件事,就是使用一个for循环并逐个打印result数组中的数据。

给定的结果

找到一个文档: {Name:bilal Email:bilal@gmail.com Password:bilalo Business:computer company}

期望的结果

Name:bilal 
Email:bilal@gmail.com 
Password:1234 
Business:computer company

代码

// 根据电子邮件和密码在数据库中查找数据
var result Store
collection := client.Database("PMS").Collection("dataStored")
if err = collection.FindOne(context.TODO(), bson.M{"email": myEmail, "password": myPassword}).Decode(&result); err != nil {
	log.Fatal(err)
}
fmt.Printf("找到一个文档: %+v\n", result)

for _, results := range result {
	fmt.Println(results)
}
英文:

In this code, I am finding the data based on email and password. But I want to do another thing that is to use a for loop and print the result array data one by one.

Given result

Found a single document: {Name:bilal Email:bilal@gmail.com Password:bilalo Business:computer company}

Expected result

Name:bilal 
Email:bilal@gmail.com 
Password:1234 
Business:computer company

Code

// Find data in database based on email and password
var result Store
collection := client.Database("PMS").Collection("dataStored")
if err = collection.FindOne(context.TODO(), bson.M{"email": myEmail, "password": myPassword}).Decode(&result); err != nil {
	log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)

for _, results := range &result {
	fmt.Println(results)
}

答案1

得分: 1

在循环之前尝试使用以下的printf语句:

fmt.Printf("Name:%v \nEmail:%v \nPassword:%v \nBusiness:%v \n", result.Name, result.Email, result.Password, result.Business)
英文:

Try this printf before the loop

fmt.Printf("Name:%v \nEmail:%v \nPassword:%v \nBusiness:%v \n", result.Name, result.Email, result.Password, result.Business)

huangapple
  • 本文由 发表于 2021年5月21日 23:25:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/67639749.html
匿名

发表评论

匿名网友

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

确定