我有以下结构。我有方法csv将返回以逗号分隔值连接字符串中的字段。
package main
import (
"bytes"
"strconv"
)
type Event struct {
B_id string
B_nam string
B_typ int
B_uuid string
B_mj_id int
B_mi_id int
B_uid string
B_url string
B_mac string
E_typ string
E_time string
C_id string
D_os string
D_os_v string
D_nam string
D_v string
Br_nam string
Br_v string
A_pkg string
A_id string
M_u_id string
bn_id string
}
func (e *Event) Csv() string {
var buffer bytes.Buffer
var comma string = ","
buffer.WriteString(e.B_id)
buffer.WriteString(comma)
buffer.WriteString(e.B_nam)
buffer.WriteString(comma)
buffer.WriteString(strconv.Itoa(e.B_typ))
buffer.WriteString(comma)
buffer.WriteString(e.B_uuid)
buffer.WriteString(comma)
buffer.WriteString(strconv.Itoa(e.B_mj_id))
buffer.WriteString(comma)
buffer.WriteString(strconv.Itoa(e.B_mi_id))
buffer.WriteString(comma)
buffer.WriteString(e.B_uid)
buffer.WriteString(comma)
buffer.WriteString(e.B_url)
buffer.WriteString(comma)
buffer.WriteString(e.B_mac)
buffer.WriteString(comma)
buffer.WriteString(e.E_typ)
buffer.WriteString(comma)
buffer.WriteString(e.E_time)
buffer.WriteString(comma)
buffer.WriteString(e.C_id)
buffer.WriteString(comma)
buffer.WriteString(e.D_os)
buffer.WriteString(comma)
buffer.WriteString(e.D_os_v)
buffer.WriteString(comma)
buffer.WriteString(e.D_nam)
buffer.WriteString(comma)
buffer.WriteString(e.D_v)
buffer.WriteString(comma)
buffer.WriteString(e.Br_nam)
buffer.WriteString(comma)
buffer.WriteString(e.Br_v)
buffer.WriteString(comma)
buffer.WriteString(e.A_pkg)
buffer.WriteString(comma)
buffer.WriteString(e.A_id)
buffer.WriteString(comma)
buffer.WriteString(e.M_u_id)
buffer.WriteString(comma)
buffer.WriteString(e.bn_id)
return buffer.String()
}
在这里你可以看到我在缓冲区中添加每个字段并将其作为字符串返回。这段代码看起来不太好。
是否可以动态获取字段值?像,
func (e *Event) Csv() string {
var buffer bytes.Buffer
var comma string = ","
var x [22]string fieldValues = //Somehow get the field Values
for i := 0; i < 22; i++ {
buffer.WriteString(B_id)
buffer.WriteString(comma)
}
return buffer.String()
}
答案 0 :(得分:3)
使用reflect迭代结构字段。
以下是示例:
package main
import (
"fmt"
"reflect"
"strings"
)
type Event struct {
B_id string
B_nam string
B_typ string
B_uuid string
B_mj_id string
B_mi_id string
B_uid string
B_url string
B_mac string
E_typ string
E_time string
C_id string
D_os string
D_os_v string
D_nam string
D_v string
Br_nam string
Br_v string
A_pkg string
A_id string
M_u_id string
// bn_id string //FIXME: unexported fields not work for reflection?
}
func main() {
// initialize your struct, I only take a few of fields as example.
e := Event{A_id: "hah", M_u_id: "dadas"}
v := reflect.ValueOf(e)
values := make([]string, v.NumField())
for i := 0; i < v.NumField(); i++ {
values[i] = v.Field(i).String()
}
fmt.Println(strings.Join(values, ","))
}
愿这有用。