douwei9759 2019-07-18 12:07
浏览 137
已采纳

如何在忽略空字符串的情况下连接结构的字符串字段?

I am really new to Go, so want some advice. I have a struct:

type Employee struct {
    Name        string
    Designation string
    Department  string
    Salary      int
    Email       string
}

I want to concatenate the string fields into a type of employee description. So that, I can say: toString(employee) and get:

John Smith Manager Sales john.smith@example.com

I tried to fetch each field, check if they are empty and put them in a slice and join them at the end

employeeDescArr := make([]string, 0, 4)
if strings.TrimSpace(value) != "" {
    append(employee.GetName(), value)
}...
return strings.Join(employeeDescArr[:], " ")

I think this method is very verbose and shows lack of Go skills. Is it better to use a string Builder instead? Is there a way to iterate through all fields of a struct in a Reflection way and join them?

  • 写回答

4条回答 默认 最新

  • douhui1333 2019-07-18 14:01
    关注

    Loop through the string fields and collect non-empty strings. Join the fields.

    func (e *Employee) String() string {
        var parts []string
        for _, s := range []string{e.Name, e.Designation, e.Department, e.Email} {
            if strings.TrimSpace(s) != "" {
                parts = append(parts, s)
            }
        }
        return strings.Join(parts, " ")
    }
    

    Because the strings.Join function is implemented using strings.Builder, there's no benefit to replacing strings.Join with application code that uses strings.Builder.

    Here's how to use reflect to avoid listing the fields in the string function:

    var stringType = reflect.TypeOf("")
    
    func (e *Employee) String() string {
        v := reflect.ValueOf(e).Elem()
        var parts []string
        for i := 0; i < v.NumField(); i++ {
            f := v.Field(i)
            if f.Type() == stringType {
                s := f.String()
                if strings.TrimSpace(s) != "" {
                    parts = append(parts, s)
                }
            }
        }
        return strings.Join(parts, " ")
    }
    

    If you want to include all fields (include non-strings and empty strings), then you can fmt.Sprint(e) to get a string. See https://play.golang.org/p/yntZxQ-Xs6C.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog