try to fill slice with struct and method in golang

Issue

I want to create a struct movie with the property title and genre data type string, then duration and year data type integer
then create a function with the name addDataFilm to add the data object from the struct to the dataFilm slice, then display the data:

like this

this is my code :

type movie struct {
    title, genre   string
    duration, year int
}

func (m movie) addDataFilm(title string, genre string, duration int, year int, dataFilm *[]string) {
    var d = strconv.Itoa(m.duration)
    var y = strconv.Itoa(m.year)
    *dataFilm = append(*dataFilm, m.title, m.genre, d, y)
}

func main(){
        var dataFim = []string{}
    var dd = movie{}

    dd.addDataFilm("LOTR", "action", 120, 1999, &dataFim)
    dd.addDataFilm("Avanger", "action", 120, 2004, &dataFim)
    dd.addDataFilm("Spiderman", "action", 120, 2004, &dataFim)
    dd.addDataFilm("Juon", "horror", 120, 2004, &dataFim)

    fmt.Println(dataFim)
}

all i got is :

this

any help will be appreciated. thank you in advance

Solution

Create a slice of movies. Append each movie to the slice. To print, range over the slice and print each movie.

var movies []*movie
movies = append(movies, &movie{"LOTR", "action", 120, 1999})
movies = append(movies, &movie{"Avanger", "action", 120, 2004})
movies = append(movies, &movie{"Spiderman", "action", 120, 2004})
movies = append(movies, &movie{"Juon", "horror", 120, 2004})
for i, m := range movies {
    fmt.Printf("%d. Title: %s\n   Genre: %s\n   Duration: %d\n   Year: %d\n\n", i+1, m.title, m.genre, m.duration, m.year)
}

Run the program on the playground.

The logic can be wrapped up in a type:

// dataFilms stores data for multiple films.
type dataFilms []*movie

func (df *dataFilms) add(title string, genre string, duration int, year int) {
    *df = append(*df, &movie{title, genre, duration, year})
}

func (df dataFilms) print() {
    for i, m := range df {
        fmt.Printf("%d. Title: %s\n   Genre: %s\n   Duration: %d\n   Year: %d\n\n", i+1, m.title, m.genre, m.duration, m.year)
    }
}

func main() {
    var df dataFilms
    df.add("LOTR", "action", 120, 1999)
    df.add("Avanger", "action", 120, 2004)
    df.add("Spiderman", "action", 120, 2004)
    df.add("Juon", "horror", 120, 2004)
    df.print()
}

Run it on the playground.

Answered By – Zombo

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.