本文发布于Cylon的收藏册,转载请著名原文链接~

string in mutual conversion

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// int to int64
m := int64(n)

// int64 to int
n := int(m)

// string to int
int,err := strconv.Atoi(string)

// string to int64
int64, err := strconv.ParseInt(string, 10, 64)

// int to string
string := strconv.Itoa(int)

// int64 to string
string := strconv.FormatInt(int64,10)

// custom type string to string
// useful link
// https://stackoverflow.com/questions/45891600/converting-a-custom-type-to-string-in-go
  type CustomType string
  Foobar CustomType = "somestring"
// error
  var a string
  a = Foobar
// correct
  var a string
  a = string(Foobar)

slice to struct

Question: in golang how to convert slice to struct

scene 1:use reflect convert slice to struct

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
func SliceToStruct(array interface{}) (forwardPort *ForwardPort, err error) {
	forwardPort = &ForwardPort{}
	valueOf := reflect.ValueOf(forwardPort)
	if valueOf.Kind() != reflect.Ptr {
		return nil, errors.New("must ptr")
	}
	valueOf = valueOf.Elem()
	if valueOf.Kind() != reflect.Struct {
		return nil, errors.New("must struct")
	}

	switch array.(type) {
	case []string:
		arrayImplement := array.([]string)
		for i := 0; i < valueOf.NumField(); i++ {
			if i >= len(arrayImplement) {
				break
			}
			val := arrayImplement[i]
			if val != "" && reflect.ValueOf(val).Kind() == valueOf.Field(i).Kind() {
				valueOf.Field(i).Set(reflect.ValueOf(val))
			}
		}
	case []interface{}:
		arrayImplement := array.([]interface{})
		for i := 0; i < valueOf.NumField(); i++ {
			if i >= len(arrayImplement) {
				break
			}
			val := arrayImplement[i]
			if val != "" && reflect.ValueOf(val).Kind() == valueOf.Field(i).Kind() {
				valueOf.Field(i).Set(reflect.ValueOf(val))
			}
		}
	}

	return forwardPort, nil
}

struct to anything

https://github.com/fatih/structs

byte json to map

json实例如下所示,要求转换结果是需要data,这个是haproxy dataplane api的数据结构

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{
    "_version": 14,
    "data": [
        {
            "name": "http",
            "address": "127.0.0.1",
            "port": 80
        }
    ]
}

此时无需定义一个结构体,使用 map即可完成

1
2
3
4
5
// frist, define a map struct
bindList := map[string][]models.Bind{}

// convert with json.Unmarshal
json.Unmarshal(resp, &bindList)

Notes:这里不要去判断error,因为"_version" 字段是一个int类型,必然是 != nil ,转换时正确格式的会被转换,错误格式则被忽略报错了

本文发布于Cylon的收藏册,转载请著名原文链接~

链接:https://www.oomkill.com/2019/10/goskill-golang-type-convert/

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」 许可协议进行许可。