Difference between structs and intefaces?

Hey, glad to be here agian :wink:

I’ve a little problem when I program in Golang…

I don’t know the difference between structs and interfaces.

I thought it was about properties for “structs” and methods for “interfaces” but I am not sure yet…

Can anyone explain me ?

Basically this.

Structure define data associated with behaviour through methods.

Interfaces define common behaviour that can be implemented by many different structs. But interfaces do not make any guarantees about actual data.

1 Like

OK, I have this code :

type Website struct {
   Name        string `json:"name"`
   Description string `json:"description"`
   Url         string `json:"url"`
}

var websites []Website

I’ve already used Typescript in JS and when I use []Website in Typescript it’s because Website is an interface just like the struct I did… So when do I have to use interfaces and when do I have to use structs ?

I recommend walking through the tour to understand the basics: https://tour.golang.org/

Interfaces start on page nine, but the pages leading up to it talking about structs, methods, and receivers are useful for understanding interfaces.

4 Likes

Thanks :blush::wink:

An interface defines a set of methods that you’re going to support for multiple different types of struct. This allows you to write methods which work for any struct which supports the interface, rather than only for a particular type of struct.

The structs implement the interface by implementing the set of methods required.

Thanks for you I understand Interface now :blush:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.