#generic field content

13 messages · Page 1 of 1 (latest)

pallid turret
#
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    dataBytes := []byte{}
    idx := uint8(0)

    // Store values of type user into the list.
    fmt.Println("listAnys=>")
    var listAnys list[any]
    listAnysP1 := listAnys.add(user{"Bill", idx + 1})
    listAnysP2 := listAnys.add(user{"Ale", idx + 2})
    listAnysP3 := listAnys.add(handler{"Bob", 1, idx + 3})
    fmt.Println(listAnysP1.Data, listAnysP2.Data, listAnysP3.Data)
    dataBytes, _ = json.Marshal(listAnysP2)
    fmt.Println("\tlistAnysP2:", string(dataBytes))
    dataBytes, _ = json.Marshal(listAnysP2.Data)
    fmt.Println("\tlistAnysP2.Data:", string(dataBytes))
    dataBytes, _ = json.Marshal(listAnysP2.Prev) // <-----how do I print the content?
    fmt.Println("\tlistAnysP2.Prev:", string(dataBytes))
    dataBytes, _ = json.Marshal(listAnysP2.Next) // <-----how do I print the content?
    fmt.Println("\tlistAnysP2.Next:", string(dataBytes))

    var listPointers list[*user]
    listPointersP1 := listPointers.add(&user{"Bill", idx + 1})
    listPointersP2 := listPointers.add(&user{"Ale", idx + 2})
    fmt.Println(listPointersP1.Data, listPointersP2.Data)
}

type user struct {
    Name string `json:"name"`
    Idx  uint8  `json:"idx"`
}

type handler struct {
    Name string `json:"name"`
    Num  int    `json:"num"`
    Idx  uint8  `json:"idx"`
}

type node[T any] struct {
    Data T        `json:"data"`
    Next *node[T] `json:"next"`
    Prev *node[T] `json:"prev"`
}

type list[T any] struct {
    First *node[T] `json:"first"`
    Last  *node[T] `json:"last"`
}

func (l *list[T]) add(data T) *node[T] {
    n := node[T]{
        Data: data,
        Prev: l.Last,
    }
    if l.First == nil {
        l.First = &n
        l.Last = &n
        return &n
    }
    l.Last = &n
    l.Last.Next = &n
    return &n
}

how do I print generic type field content?
https://go.dev/play/p/3BS3ktPJICM

real reef
#

im not sure i understand the question, does doing that not work?

pallid turret
#

it showed null, but if you add

if listAnysP2.Next == nil {
        fmt.Println("!!!")
    }

this line won't be executed, it means it is not nil

real reef
pallid turret
#

thx, I aware that error now.
But how could I print the value in listAnysP2.Next?

I tried

  1. json
    => not work on a cyclic
  2. fmt.Printf("\tlistAnysP2.Next: %+v\n", listAnysP2.Next)
    => listAnysP2.Next: &{Data:{Name:Ale Idx:2} Next:0x1400013e020 Prev:0x1400013e000}
    => only showed memory location
fossil surge
#

you need implement your own MarshalJSON method

pallid turret
real reef
#

json doesnt have concepts of references, so the json for a cyclic reference is infinite in size

fossil surge
#
    l.Last = &n
    l.Last.Next = &n

this is a wrong logic btw

#

you are doing &n.Next = &n

#

you may want reverse the order