SoFunction
Updated on 2025-03-03

Go checks whether there is a field in the structure and creates a structure slice or map

Verify that field Z exists in the structure type Test

The following code snippet declares the structure type Test with fields A, B, and C. We need to verify that field Z exists in the structure type Test.

Sample code:

package main
import (
	"log"
	"reflect"
)
func main() {
	type test struct {
		A bool
		B bool
		C bool
	}
	v := new(test)
	metaValue := (v).Elem()
	for _, name := range []string{"A", "C", "Z"} {
		field := (name)
		if field == ({}) {
			("Field %s not exist in struct", name)
		}
	}
}

Output:

2009/11/10 23:00:00 Field Z not exist in struct

Create a slicing of structures

Sample code:

package main
import (
	"fmt"
)
type Widget struct {
	id    int
	attrs []string
}
func main() {
	widgets := []Widget{
		Widget{
			id:    10,
			attrs: []string{"blah", "foo"},
		},
		Widget{
			id:    11,
			attrs: []string{"foo", "bar"},
		},
		Widget{
			id:    12,
			attrs: []string{"xyz"},
		},
	}
	for _, j := range widgets {
		("%d ", )
		for _, y := range  {
			(" %s ", y)
		}
		()
	}
}

Output:

10  blah  foo 
11  foo  bar
12  xyz

Create a structure map

Sample code:

package main

import "fmt"

type Emp struct {
	x int
	y []string
}

func main() {
	var list = map[string]*Emp{"e1": {1001, []string{"John", "US"}}}

	e := new(Emp)
	 = 1002
	 = []string{"Rock", "UK"}

	list["e2"] = e

	(list["e1"])
	(list["e2"])
}

Output:

&{1001 [John US]}
&{1002 [Rock UK]}

The above is the detailed content of Go checking whether there is a certain field in the structure and creating structure slices or maps. For more information about Go structure inspection creation, please pay attention to my other related articles!