An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
March 9, 2021 02:56 pm GMT
Original Link: https://dev.to/johnleoclaudio/go-struct-3p48
Go Struct
Go lets you create your own data type using structs
. If you're coming from TypeScript, you can think of it like an interface
where you declare your fields and specify each type.
type User struct { name string age int}
To access values, use dot notation. Here's an example to use it:
// variable user1 is now a type Useruser1 := User{ name: "Scott", age: 23,}// Display the values:fmt.Println("Name", user1.name)fmt.Println("Age", user1.age)
Here are some gotchas:
type bob struct { name string age int}type annie struct { name string age int}var b bobvar a annieb = a // <- cannot use a (variable of type annie) as bob value in assignment
Although the bob
and annie
structs have the same fields, assigning the variable b
with a
won't work because Go doesn't do implicit conversion
.
You CAN assign a
to b
though, using explicit
conversion
b = bob(a)
What do you think will happen in the code below? Will the compiler complain?
user2 := struct { name string age int}{ name: "Ishin", age: 72,}b = user2a = user2
Surprisingly, the code above works. Why this works and not the previous one? It's because variable a
was a named type
and variable user2
is a literal type
.
Key Takeaways:
- Structs lets you create your own data type
- Use
explicit
conversion to assign values with same memory footprint
Original Link: https://dev.to/johnleoclaudio/go-struct-3p48
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To