Hi Everyone,
Let's try to understand, Struct and Interface in Go programming language
Struct -
struct is also called as structure, so normally we have some built in data types which are provided by the language, such as int, float64, string, bool etc
but suppose we want to create our own custom data type, how can we achieve this ? so in order to solve this problem we can use struct which helps us to create our own custom data type in which related data is grouped together, once we have this new custom data type, we can use it in our programs, like when when declaring a variable or when declaring and assigning the value
what problem structs are solving ?
If we want to represent a real-world entity in our program we don't have any type for it, so to solve this problem, Golang provides us structs, which allow us to group related data together and create a custom type.
for example -
suppose we want to store data of 100 users, so we have a program which ask us to enter details of a user like name, email, phone and address and then storing it, and after that it will ask us whether we want add the data of another user or not, this we way we need to add the data of 100 users.
Now question is where we are storing this data ?
one approach is we create separate arrays or slices for each property and then store the data , but the problem is, the data is not grouped together as it is stored separately
But what we wanted to achieve, is to keep the related data together right, hence we use use structs which helps us to create a type of similar data
type User struct {
name string
email string
phone string
address string
}
so to solve above problem of storing data of 100 users, what we can do is since we have a new type "User", so we can create an array or a slice of "User" type
var users [100]User
var users []User
Interview Answer -
Golang provides us built-in data types such as int, float64, string, bool etc. But when we want to represent a real-world entity in our program we don't have any type for it, so to solve this problem, Golang provides us structs, which allow us to group related data together and create a custom type.
Interface -
An interface focuses on behavior instead of the actual type.
example 1:
suppose we have -
Dog
Cat
Human
All of them are different types, but all of them can perform one common action - Speak()
Now instead of writing separate code for Dog, Cat, and Human, we can write code that works with anything that can Speak().
This idea of focusing on behavior is called an interface.
package main
import "fmt"
type Speaker interface {
speak()
}
type Dog struct {}
func (d Dog) speak() {
fmt.Println("Dog")
}
type Cat struct {}
func (c Cat) speak() {
fmt.Println("Cat")
}
type Human struct {}
func (h Human) speak() {
fmt.Println("Human")
}
func speaking(s Speaker) {
s.speak()
}
func main() {
speaking(Dog{})
speaking(Cat{})
speaking(Human{})
}
Top comments (0)