notalentgeek
notalentgeek

Reputation: 5779

How Can I Access `struct` 's Field in a New `type` of That `struct` slice?

The codes are like these

package main

import "fmt"

type Hello struct {
    ID  int
    Raw string
}

type World []*Hello

func HelloWorld() *World {
    return &World{
        {
            ID:  1,
            Raw: "asd",
        },
        {
            ID:  2,
            Raw: "jkf",
        },
    }
}

func main() {
    something := HelloWorld()

    // What I want to achieve...
    fmt.Println(something[0].Raw) // This should return `"asd"`.
}

But I got this error ---> ./prog.go:29:23: invalid operation: something[0] (type *World does not support indexing). How can I get Raw from something?

Upvotes: 0

Views: 43

Answers (1)

Eklavya
Eklavya

Reputation: 18430

Use (*something)[0].Raw because something is a pointer of World type.

We need to use * operator, also called dereferencing operator which if placed before a pointer variable and it returns the data in that memory.

fmt.Println((*something)[0].Raw) 

Upvotes: 1

Related Questions