Struct and Interface in Go

tim.chenbw
1 min readAug 8, 2021

--

You can also get the same post in my blog : https://bwbwchen.github.io/posts/go-struct-interface/

We can think of struct as a wrapper of object. You can also check Golang spec (struct).

struct example

We use Interface to group a set of method. You can think it as a list that all structs that have implemented the required method. If you missing one of the method, you can not in that interface.

You can also check Golang spec (interface).

interface example

We can see that Student, Worker, Human all have implemented the Info method, so the variable i with type person interface will work well.

output:

I am Tom. I am a student.I am Ben. I am a worker. I have 1000 salaryI am SusanI am Tom. I am a student.I am Ben. I am a worker. I have 1000 salaryI am Susan

But what if I change the Human method to Hi() ?

output :

cannot use Susan (type Human) as type Person in assignment:Human does not implement Person (missing Info method)

If you have any problem, feel free to ask me !

You can find me here 👉 tim.chenbw@gmail.com

--

--

tim.chenbw

I am Bo-Wei Chen. Skilled in Data Analytics, Parallel programming and Backend developement with a Computer science Bachelor’s degree from NTHU.