Can I pass struct as a function param in golang

2023-07-17by@tim&@ChatGPT.Model: gpt-3.5-turbo-16k
tim

Can I pass struct as a function param in golang

Avatar
Avatar

Yes, you can pass a struct as a function parameter in Golang.

Here is an example:

package main

import "fmt"

// Define a struct
type Person struct {
    Name string
    Age  int
}

// Function that takes a struct as a parameter
func printInfo(p Person) {
    fmt.Printf("Name: %s, Age: %d\n", p.Name, p.Age)
}

func main() {
    // Create an instance of the struct
    person := Person{Name: "John", Age: 20}

    // Pass the struct to the function
    printInfo(person)
}

In this example, Person is a struct type with two fields Name and Age. The printInfo function takes a Person struct as a parameter and prints its information. In the main function, an instance of Person struct is created and passed to printInfo function.

tim

can i pass any struct to a function

Avatar
Avatar

Yes, you can pass any struct to a function in Golang. The struct can be defined within the same package or imported from another package.

Here is an example:

package main

import "fmt"

// Define a struct
type Person struct {
    Name string
    Age  int
}

// Function that takes a struct as a parameter
func printInfo(p interface{}) {
    switch v := p.(type) {
    case Person:
        fmt.Printf("Name: %s, Age: %d\n", v.Name, v.Age)
    default:
        fmt.Println("Unsupported struct type")
    }
}

func main() {
    // Create an instance of the struct
    person := Person{Name: "John", Age: 20}

    // Pass the struct to the function
    printInfo(person)
}

In this example, the printInfo function takes an interface{} parameter, which means it can accept any type of struct. Inside the function, you can use a type switch to determine the type of the passed struct, and then perform specific actions based on the type.

Note that using an empty interface{} as a function parameter allows you to accept any type, but you will need to use type assertions or type switches inside the function to work with the struct.