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

  1. // 错误代码
  2. func myfunc(arg ...int) {
  3. for _, n := range arg {
  4. fmt.Printf("And the number is: %d\n", n)
  5. }
  6. }
  7. func main() {
  8. fmt.Printf(myfunc(1, 2, 3, 4, 5))
  9. }
  10.  
  11. // 报错 myfunc(1, 2, 3, 4, 5) used as value
  12.  
  13. // 正确代码
  14. func myfunc(arg ...int) {
  15. for _, n := range arg {
  16. fmt.Printf("And the number is: %d\n", n)
  17. }
  18. }
  19. func main() {
  20. myfunc(1, 2, 3, 4, 5)
  21. }
  22. // 结果:
  23. //And the number is: 1
  24. //And the number is: 2
  25. //And the number is: 3
  26. //And the number is: 4
  27. //And the number is: 5
  28.  
  29. // 或者 正确代码
  30. func myfunc(arg ...int) int {
  31. m := 0
  32. for _, n := range arg {
  33. m += n
  34. }
  35. return m
  36. }
  37. func main() {
  38. fmt.Printf("m = %d", myfunc(1, 2, 3, 4, 5))
  39. }
  40. // 结果:m = 15

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

随机推荐

  1. ignore_user_abort(true); set_time_limit(0);程序在本地测试可以一直运行,上传服务器只能运行10-15分钟

    当PHP运行在安全模式下时此函数无效.除了关闭安全模式或者在php.ini程序中修改最大运行时间没有其他办法让此函数运行. php.ini 中缺省的最长执行时间是 30 秒,这是由 php.ini 中 ...

  2. centos----------centos下如何安装phpstorm

    1.首先打开centos下的谷歌浏览器,找到phpstorm官网下载linux版本.PhpStorm-2016.3.2.tar.gz 2.然后gunzip PhpStorm-2016.3.2.tar. ...

  3. Divide the Sequence (贪心)

    题意:求将一串数据尽可能多分成所有前缀和大于0的连续子串. 思路:由于是要求所有前缀和大于0,那么只要从后往前推就好了. #include<bits/stdc++.h> using nam ...

  4. vue运行时 eslint 报“import/first” WARN deprecated browserslist 问题解决

    vue运行时 eslint 报“import/first”  WARN deprecated browserslist 问题解决 这个信息的意思是导入文件顺序不对,绝对导入应该放在相对导入前面.将绝对 ...

  5. Windows cmd 一些命令

    运行是Windows的必要组成部分,可以简单理解为一个应用程序快速调用的组件.通过“运行”窗口,可以调用Windows中任何应用程序甚至DOS命令.一般可以搜索百度百科 微软件(窗口) + R    ...

  6. centos crash debug

    https://www.dedoimedo.com/computers/crash.html#mozTocId484074 http://people.redhat.com/anderson/cras ...

  7. 5、Kafka生产过程分析

    1.写入方式 producer采用推(push)模式将消息发布到broker, 每条消息都被追加(append)到分区(patition)中,属于顺序写磁盘(顺序写磁盘效率比随机写内存要高,保障kaf ...

  8. Python socket ssh接收大数据

    通过socket连续接收返回数据 Server服务端 import socket,os server = socket.socket() server.bind(('localhost',9999)) ...

  9. 在数据库级别还是在service层进行级联删除

    在数据库配置级联删除的话,父表删除子表也删除.但是应该将维护代码放在一处,不要在service上删除父表,而在数据库层面级联删除子表,应该都在service层上进行删除.

  10. kettle 连接 SQL Server 异常

    场景重现 新安装的 kettle(pdi-ce-7.0.0.0-25) 连接 SQL Server 2012 时报错如下: 解决办法 到 https://sourceforge.net/project ...