Go语言 指向JSON的指针数组[duplicate]

46scxncf  于 2023-06-19  发布在  Go
关注(0)|答案(1)|浏览(104)

此问题已在此处有答案

json.Marshal(struct) returns "{}"(3个答案)
Golang parse JSON returns 0(2个答案)
6天前关闭
在golang中,我有指向struct的指针的二维切片,如下面的代码所示。

type point struct {
    x int
    y int
}

type cell struct {
    point   point
    visited bool
    walls   walls
}

type walls struct {
    n bool
    e bool
    s bool
    w bool
}

type maze struct {
    cells         [][]*cell
    solutionStack Stack
}

我想把细胞切片序列化成JSON。但是由于所有的元素都是指针,调用encode将给予空的JSON。序列化此切片的最佳方法是什么。
我的一个解决方案是创建这个2D切片的本地副本,并将所有指针替换为实际结构。会有用的但不行

hyrbngr7

hyrbngr71#

我不确定我是否回答了你的问题,因为内置的JSON包会自动反射指针。它应该“只是工作”。我注意到你没有导出你的结构中的属性,也许这就是你的问题?使用反射时,不能检查未导出的值。
http://play.golang.org/p/zTuMLBgGWk

package main

import (
    "encoding/json"
    "fmt"
)

type point struct {
    X int
    Y int
}

type cell struct {
    Point   point
    Visited bool
    Walls   walls
}

type walls struct {
    N bool
    E bool
    S bool
    W bool
}

type maze struct {
    Cells [][]*cell
}

func main() {
    m := maze{}

    var row1 []*cell
    var row2 []*cell

    row1 = append(row1, &cell{
        Point: point{1, 2},
        Walls: walls{N: true},
    })
    row2 = append(row2, &cell{
        Point: point{3, 4},
        Walls: walls{E: true},
    })
    m.Cells = append(m.Cells, row1, row2)

    mazeJson, _ := json.MarshalIndent(m, "", "  ")
    fmt.Println(string(mazeJson))
}

相关问题