This content originally appeared on DEV Community and was authored by John Leo Claudio
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 User
user1 := 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 bob
var a annie
b = 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 = user2
a = 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
This content originally appeared on DEV Community and was authored by John Leo Claudio

John Leo Claudio | Sciencx (2021-03-09T14:56:38+00:00) Go Struct. Retrieved from https://www.scien.cx/2021/03/09/go-struct/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.