doucan4815
2019-08-05 12:45
浏览 26
已采纳

如何将整数和nill数组转换为字符串? [关闭]

Let's say I have array with integer and nil elements:

[15698, nil, 13000, 560365, nil]

I want to convert this array to string where each element separated by ,.

[15698, null, 13000, 560365, null]

I tried next code but it return 0 instead of null. How to fix it?

func ConvertIntArrayToString(input []int) string {
    if len(input) == 0 {
        return ""
    }
    estimate := len(input) * 4
    b := make([]byte, 0, estimate)
    for _, n := range input {
        b = strconv.AppendInt(b, int64(n), 10)
        b = append(b, ',')
    }
    b = b[:len(b)-1]
    return string(b)
}

Here is how I created array:

type NilInt struct {
    value int
    null  bool
}

func (n *NilInt) Value() interface{} {
    if n.null {
        return nil
    }
    return n.value
}

func NewInt(x int) NilInt {
    return NilInt{x, false}
}

func NewNil() NilInt {
    return NilInt{0, true}
}

var x = []utils.NilInt{utils.NewNil(), utils.NewInt(10), utils.NewNil(), utils.NewInt(5)}]

var result strings.Builder

for _, n := range x {
    if n.Value() == nil {
        result.WriteString("null,")
    } else {
        result.WriteString(??? + ",")
    }
}

fmt.Println(result)

图片转代码服务由CSDN问答提供 功能建议

比方说,我有一个包含 integer nil 元素的数组 :

  [15698,nil,13000,560365,nil] 
   
 
 

我想将此数组转换为 字符串,每个元素之间用分隔。

  [15698,null,13000,560365,null] 
    
 
 

我尝试了下一个代码,但它返回0而不是null。

  func ConvertIntArrayToString(input [] int)字符串{
如果len(input)== 0 {
返回“” 
} 
 估计:= len(输入)* 4 
b:= make([] byte,0,估计)
 _,n:=范围输入{
b = strconv.AppendInt(b,int64(n),10)  
b = append(b,',')
} 
b = b [:len(b)-1] 
返回字符串(b)
} 
   
 \  n 

这是我创建数组的方式:

  type NilInt struct {
 value int 
 null bool 
} 
 \  nfunc(n * NilInt)Value()接口{} {
,如果n.null {
返回nil 
} 
返回n.value 
} 
 
func NewInt(x int)NilInt {
返回 NilInt {x,false} 
} 
 
func NewNil()NilInt {
返回NilInt {0,true} 
} 
 
var x = [] utils.NilInt {utils.NewNil(),utils。  NewInt(10),utils.NewNil(),utils.NewInt(5)}] 
 
var结果字符串。Builder
 
for _,n:= range x {
如果n.Value()== nil  {
 result.WriteString(“ null,”)
}其他{
 result.WriteString(??? +“,”)
} 
}  
 
fmt.Println(result)
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douken0530 2019-08-05 13:50
    已采纳

    As pointed out in the comments by others, an int slice ([]int) cannot contain nil values because it is illegal to assign nil to a variable of a type whose specified zero value is not nil.

    If you need a slice that can hold int values and nils you can use []interface{}. Then, to construct the desired string you can simply marshal such a slice with the encoding/json package.

    var a = []interface{}{15698, nil, 13000, 560365, nil}
    b, err := json.Marshal(a)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(b))
    

    https://play.golang.com/p/hEjTFIoJlXj

    点赞 打赏 评论

相关推荐 更多相似问题