英文:
How to pass struct as a function argument in Go?
问题
package main
import "fmt"
type Person struct {
name string
age int
job string
salary int
}
func test(class Person) {
// Access and print Pers1 info
fmt.Println("Name: ", class.name)
fmt.Println("Age: ", class.age)
fmt.Println("Job: ", class.job)
fmt.Println("Salary: ", class.salary)
}
func main() {
var pers1 Person
var pers2 Person
// Pers1 specification
pers1.name = "Hege"
pers1.age = 45
pers1.job = "Teacher"
pers1.salary = 6000
// Pers2 specification
pers2.name = "Cecilie"
pers2.age = 24
pers2.job = "Marketing"
pers2.salary = 4500
test(pers1) // Call the test function with pers1 as argument
}
这是你的代码。你想将整个结构体作为参数传递给函数test
。你可以通过以下方式实现:
- 在函数
test
的参数中指定结构体类型:func test(class Person)
- 在
main
函数中调用test
函数,并将pers1
作为参数传递:test(pers1)
这样,test
函数就可以访问和打印pers1
的信息了。
英文:
package main
import "fmt"
type Person struct {
name string
age int
job string
salary int
}
func test(class Person) {
// Access and print Pers1 info
fmt.Println("Name: ", class.name)
fmt.Println("Age: ", class.age)
fmt.Println("Job: ", class.job)
fmt.Println("Salary: ", class.salary)
}
func main() {
var pers1 Person
var pers2 Person
// Pers1 specification
pers1.name = "Hege"
pers1.age = 45
pers1.job = "Teacher"
pers1.salary = 6000
// Pers2 specification
pers2.name = "Cecilie"
pers2.age = 24
pers2.job = "Marketing"
pers2.salary = 4500
}
/* This is my code. I want to pass whole struct to a function test as argument. But i don't know the syntax of like how can i achieve this. Kindly look into this and help me*/
答案1
得分: 2
你应该将其传递给函数调用,如 test(pers1)
和 test(pers2)
。
英文:
You should pass it to function calling as test(pers1)
and test(pers2)
答案2
得分: 0
包 main
import "fmt"
type Person struct {
name string
age int
job string
salary int
}
func test(class Person) {
// 访问并打印 Pers1 的信息
fmt.Println("姓名:", class.name)
fmt.Println("年龄:", class.age)
fmt.Println("工作:", class.job)
fmt.Println("薪水:", class.salary)
}
func main() {
var pers1 Person
var pers2 Person
// Pers1 的规格
pers1.name = "Hege"
pers1.age = 45
pers1.job = "Teacher"
pers1.salary = 6000
// Pers2 的规格
test(pers1)
pers2.name = "Cecilie"
pers2.age = 24
pers2.job = "Marketing"
pers2.salary = 4500
test(pers2)
}
/* 尝试一下,你必须将其传递为 test(pers1) 和 test(pers2)。希望现在能正常工作。*/
英文:
package main
import "fmt"
type Person struct {
name string
age int
job string
salary int
}
func test(class Person) {
// Access and print Pers1 info
fmt.Println("Name: ", class.name)
fmt.Println("Age: ", class.age)
fmt.Println("Job: ", class.job)
fmt.Println("Salary: ", class.salary)
}
func main() {
var pers1 Person
var pers2 Person
// Pers1 specification
pers1.name = "Hege"
pers1.age = 45
pers1.job = "Teacher"
pers1.salary = 6000
// Pers2 specification
test(pers1)
pers2.name = "Cecilie"
pers2.age = 24
pers2.job = "Marketing"
pers2.salary = 4500
test(pers2)
}
/* Try this you have to pass it as test(pers1) and test(pers2). I hope it works fine now.*/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论