dsdeeaquu38538545 2015-09-25 16:16 采纳率: 100%
浏览 118
已采纳

Golang:如何使用TYPE声明返回的变量?

In GO, how do I declare the returned variables of a function WITH TYPE ?

e.g. I have this code

dat, err := ioutil.ReadFile("/tmp/dat")
check(err)
fmt.Print(string(dat))

but what I want is this:

var dat []byte, err error := ioutil.ReadFile("/tmp/dat")
check(err)
fmt.Print(string(dat))

However, no matter how I try, I only get this output

syntax error: unexpected comma, expecting semicolon or newline or }

I'm working without IDE, and as the number of variables increases, it's really idiotic to have to keep all the return values's types in short-term memory... let alone if somebody else has to read the code.

How can I declare the returned tuple WITH type ?

  • 写回答

1条回答 默认 最新

  • duanbei7005 2015-09-25 16:23
    关注

    That's because you're using := in your assignment there and that is a convenience syntax to declare and assign. It makes it so you don't have to provide the type, I assume the compiler just implies it by what is returned/whatever types come from the right hand side. Instead you need to do this;

    var dat []byte
    var err error
    
    dat, err = ioutil.ReadFile("/tmp/dat")
    

    But no one does this because dat, err := ioutil.ReadFile("/tmp/dat") is such a cleaner syntax.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?