Golang : Convert string slice to struct and access with reflect example
Writing this down here for my own future references. Basically, what this code does is to convert a given string data slice into struct
. Pretty handy to have when processing data output from proprietary systems.
Here you go!
package main
import (
"fmt"
"log"
"reflect"
"strconv"
)
type User struct {
Id int
Username string
}
func main() {
data := [][]string{
[]string{"1", "Adam"},
[]string{"2", "Eve"},
}
// convert data string slice to struct
// such as
//user1 := &User{"1","Adam"}
//user2 := &User{"2","Eve"}
users := []*User{}
for _, v := range data {
//fmt.Println("data: ", v[0], v[1])
// convert v[0] to type integer
id, err := strconv.Atoi(v[0])
if err != nil {
log.Fatal(err, v[0])
}
user := &User{id, v[1]}
users = append(users, user)
}
// the reflect way
for i := 0; i < 2; i++ {
u := reflect.ValueOf(users[i])
id := reflect.Indirect(u).FieldByName("Id")
name := reflect.Indirect(u).FieldByName("Username")
fmt.Println(id, name)
fmt.Println("==========")
}
}
Output:
1 Adam
==========
2 Eve
==========
Happy coding!
Reference:
https://www.socketloop.com/tutorials/golang-how-to-get-struct-field-and-value-by-name
See also : Golang : How to get struct field and value by name
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+20.1k Golang : Convert(cast) string to rune and back to string example
+12.9k Golang : syscall.Socket example
+5.2k Golang : Experimental emojis or emoticons icons programming language
+19.9k Golang : GORM create record or insert new record into database example
+12k Golang : Get user input until a command or receive a word to stop
+13.1k Golang : Find network of an IP address
+20.6k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+4.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+15.7k Golang : Find file size(disk usage) with filepath.Walk
+17.4k Golang : Check whether a network interface is up on your machine
+8.9k Golang : Edge detection with Sobel method
+18.8k Golang : Read directory content with os.Open