zoukankan      html  css  js  c++  java
  • Go used as value问题

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

    // 错误代码
    func myfunc(arg ...int) {
    	for _, n := range arg {
    		fmt.Printf("And the number is: %d
    ", 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)
    	}
    }
    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包或者给返回值进行输出。

    实践出真知~
  • 相关阅读:
    代码规范
    svn的牛逼操作反向merge
    QT 半透明遮罩(弹窗)
    ACE库 ACE_Handle_Set类解析
    linux系统如何启用ftp服务
    vim color
    Linux动态库应用
    自建工程makefile文件
    Makefile工程文件
    linux杂记
  • 原文地址:https://www.cnblogs.com/NolaLi/p/10320378.html
Copyright © 2011-2022 走看看