Home > Blockchain >  How to pass struct as a function argument in Go?
How to pass struct as a function argument in Go?

Time:09-22

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*/

CodePudding user response:

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.*/

CodePudding user response:

You should pass it to function calling as test(pers1) and test(pers2)

  •  Tags:  
  • go
  • Related