Last active
July 10, 2023 00:06
-
-
Save pedrobertao/39d6c9ef9ff46b2ce98ee64b187593b5 to your computer and use it in GitHub Desktop.
This is a simple example to use ANY in golang which is an alias for interface{}, therefore easy to read
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################# | |
## EXAMPLE OF USAGE OF ANY IN AN OBJECT/STRUCT ## | |
################################################# | |
package main | |
import "fmt" | |
const ( | |
MALE string = "male" | |
FEMALE string = "female" | |
) | |
type WildAnimal struct { | |
Name string | |
Specie string | |
Gender string | |
Habit string | |
} | |
type Animal struct { | |
Name string | |
Specie string | |
Gender string | |
} | |
type Person struct { | |
Name string | |
Surname string | |
Animals []any | |
} | |
func main() { | |
dog := Animal{ | |
Name: "Rex", | |
Specie: "Dog", | |
Gender: MALE, | |
} | |
cat := WildAnimal{ | |
Name: "Hope", | |
Specie: "Tiger", | |
Gender: FEMALE, | |
Habit: "Jungle", | |
} | |
me := Person{ | |
Name: "Pedro", | |
Surname: "Bertão", | |
Animals: []any{dog, cat}, | |
} | |
fmt.Println("Hi, I'm @pedrobertao ") | |
fmt.Println("I have two pets") | |
fmt.Printf("One is a %s named %s \n", me.Animals[0].(Animal).Specie, me.Animals[0].(Animal).Name) | |
fmt.Printf("And also I have a %s named %s that lives in the %s. \n", me.Animals[1].(WildAnimal).Specie, me.Animals[1].(WildAnimal).Name, me.Animals[1].(WildAnimal).Habit) | |
} | |
################################################################# | |
## Output ## | |
## Hi, I'm @pedrobertao ## | |
## I have two pets ## | |
## One is a Dog named Rex ## | |
## And also I have a Tiger named Hope that lives in the Jungle. ## | |
################################################################# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment