练习Go变参时遇到一个报错:used as value 代码如下:

// 错误代码
func myfunc(arg ...int) {
for _, n := range arg {
fmt.Printf("And the number is: %d\n", n)
}
}
func main() {
fmt.Printf(myfunc(1, 2, 3, 4, 5))
} // 报错 myfunc(1, 2, 3, 4, 5) used as value // 正确代码
func myfunc(arg ...int) {
for _, n := range arg {
fmt.Printf("And the number is: %d\n", n)
}
}
func main() {
myfunc(1, 2, 3, 4, 5)
}
// 结果:
//And the number is: 1
//And the number is: 2
//And the number is: 3
//And the number is: 4
//And the number is: 5 // 或者 正确代码
func myfunc(arg ...int) int {
m := 0
for _, n := range arg {
m += n
}
return m
}
func main() {
fmt.Printf("m = %d", myfunc(1, 2, 3, 4, 5))
}
// 结果:m = 15

  从上面代码可以看出myfunc()函数是没有返回值的,直接调用就可以,不需要使用fmt包或者给返回值进行输出。

随机推荐

  1. SQLite multiple threads

    const int loops = 1000; public void DatabaseThreadSafetyTest() { var backgroundThread = new Thread(n ...

  2. 【Checkio Exercise】Robot Sort

    Robot Sort All of the refined ingots should be sorted by size in each lot while passing by on a conv ...

  3. Android Studio 添加已经移除的Module

    Android Studio 删除Module时,需要先在Project Structure中点击“-”来移除,此时小手机图标消失,但是这个时候Module并没有在硬盘中删除,只是和这个Project ...

  4. Python基础(六)_全局变量声明、可变参数、关键字参数

    1. global声明全局变量 #声明name这个变量为全局变量,只是写在函数里面 #写代码时,尽量不要用全局变量,会一直占用内存.       ------->{'name':'abc','s ...

  5. MySQL插入去重命令_REPLACE INTO

    以主键和unique索引为依据. INSERT INTO:表中不存在对应的记录,则插入:若存在对应的记录,则报错: INSERT IGNORE INTO:表中不存在对应的记录,则插入:若存在对应的记录 ...

  6. phpstorm2018激活方法

    直接用浏览器打开 http://idea.lanyus.com/点击页面中的“获得注册码”,然后在注册时切换至Activation Code选项,输入获得的注册码一长串字符串如果提示红字体信息,那么先 ...

  7. iptables 认识 第二章

    一.四表五链 netfilter 通过四表五链两个维度来定义数据包过滤规则. #上面图片中 raw 表不在postrouting 链中,请注意 上图中的五个位置也被称为五个钩子函数(hook func ...

  8. 剑指offer(7)斐波那契数列

    题目描述 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项. n<=39 题目分析 我们都知道斐波那契可以用递归,但是递归重复计算的部分太多了(虽然可以通过),但是这 ...

  9. Intellj IDEA光标问题

    Intellj IDEA光标为insert状态,无法删除内容以前用得是社区版的IDEA,今天装了14版本的,结果导入项目后,发现打开java文件的光标是win系统下按了insert键后的那种宽的光标, ...

  10. jQuery页面替换+php代码实现搜索后分页

    HTML代码 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <ti ...