duanbo6871 2018-06-16 00:43
浏览 36
已采纳

如何用扫描值填充切片

I'm brand new to Go and having trouble getting fmt.scan() to fill a slice. The number of input values is dynamic and I can't use a for loop. My initial thought was to try this:

package main

import "fmt"

func main() {
    var x []int
    fmt.Println("Enter input")
    fmt.Scanf("%v", append(x))
    fmt.Println(x)
}

Which obviously doesn't work. Can someone point me in the right direction?

  • 写回答

1条回答 默认 最新

  • dougang1965 2018-06-16 02:03
    关注

    [Get] fmt.Scan() to fill a slice. The number of input values is dynamic and I can't use a for loop.


    Perhaps, something like this:

    package main
    
    import "fmt"
    
    func input(x []int, err error) []int {
        if err != nil {
            return x
        }
        var d int
        n, err := fmt.Scanf("%d", &d)
        if n == 1 {
            x = append(x, d)
        }
        return input(x, err)
    }
    
    func main() {
        fmt.Println("Enter input:")
        x := input([]int{}, nil)
        fmt.Println("Input:", x)
    }
    

    Output:

    Enter input:
     1
    2 3
    4
     5  6  7
    
    Input: [1 2 3 4 5 6 7]
    

    ADDENDUM:

    When storage is allocated for a variable or a new value is created, and no explicit initialization is provided, the variable or value is given a default value, the zero value for its type: nil for slices. Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T. []int(nil) is a conversion to the zero value for the slice value []int.

    x := input([]int(nil), nil)
    

    is equivalent to

    x := input([]int{}, nil)
    

    or

    var x []int
    x = input(x, nil)
    

    I have revised my answer to use:

    x := input([]int{}, nil)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集