duanpiao6679 2017-08-19 03:00
浏览 19
已采纳

将数组解压缩作为path的参数。

I want to unpack string array and pass to path.Join

package main

import (
    "fmt"
    "path"
)

func main() {
    p := []string{"a", "b", "c"}
    fmt.Println(path.Join(p...))
}

Output of this code is:

a/b/c

But if I pass arguments like:

package main

import (
    "fmt"
    "path"
)

func main() {
    p := []string{"a", "b", "c"}
    fmt.Println(path.Join("d", p...))
}

It doesn't work.

tmp/sandbox299218161/main.go:10: too many arguments in call to path.Join
    have (string, []string...)
    want (...string)

I think I have misunderstanding on unpacking, any suggestions?

  • 写回答

1条回答 默认 最新

  • dsfgdsjfd78773 2017-08-19 03:11
    关注

    You're not misunderstanding anything really, you just can't do that. The spec says:

    If the final argument is assignable to a slice type []T, it may be passed unchanged as the value for a ...T parameter if the argument is followed by .... In this case no new slice is created.

    In short, p... can only be used as the entire variadic part of the arguments, because when you do that, it simply re-uses p as the parameter slice within the function, instead of making a new one.

    If you want to add some arguments at the beginning, you would have to construct your own slice with all of the arguments first, something like:

    p := []string{"a", "b", "c"}
    p2 := append([]string{"d"}, p...)
    fmt.Println(path.Join(p2...))
    

    which works alright and prints "d/a/b/c".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图