douba8048
2017-02-06 18:00
浏览 1.2k
已采纳

在golang中将字符串转换为整数数组

I am looking for an answer in internet but it no one that fit my needs.

I have a string in the following format:

"[2,15,23]"

and i am trying to convert it in this format:

[2,15,23]

I need the type after the convertion to change to []int. I need to convert it because i want to use it later to make an interface type to use it in a sql query as param.

Is there any way to convert it?

Thanks

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

我正在互联网上寻找答案,但没有一个适合我的需求。 \ n

我有以下格式的字符串:

 “ [2,15,23]” 
   
 
  

并且我正在尝试将其转换为以下格式:

  [2,15,23] 
   
 
 <  p>我需要转换后的类型更改为[] int。 我需要转换它,因为我想稍后再使用它来使接口类型在sql查询中用作参数。 
 
 

有没有办法转换它?

谢谢

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doubiao1734 2017-02-06 20:14
    已采纳

    A better way using json.Unmarshal:

    func main() {
        str := "[2,15,23]"
        var ints []int
        err := json.Unmarshal([]byte(str), &ints)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%v", ints)
    }
    
    点赞 打赏 评论
  • dtt5830659 2017-02-06 19:17

    Here is a working example if you haven't figured it out based on the comments suggesting that you use json.Unmarshal

    Playground link

    package main
    
    import (
        "fmt"
        "log"
        "encoding/json"
    )
    
    func main() {
        str := "[2,15,23]"
        ints, err := convertToIntSlice(str)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%v", ints)
    }
    
    type IntSlice struct {
        Ints []int
    }
    
    func convertToIntSlice(s string) ([]int, error) {
        a := &IntSlice{}
        err := json.Unmarshal([]byte(`{"Ints":`+s+"}"), a)
        return a.Ints, err
    }
    
    点赞 打赏 评论
  • drsh30452 2017-02-06 19:18

    This is slightly hackish but you could treat it like a csv:

    import (
        "encoding/csv"
        "strings"
    )
    
    in := `"[2,15,23]"`
    r := csv.NewReader(strings.NewReader(in))
    
    records, err := r.ReadAll()
    
    点赞 打赏 评论

相关推荐 更多相似问题