doubi3996 2017-07-09 21:31
浏览 61
已采纳

如何定义一个空变量来存储File结构的值?

I am trying to figure out a way to declare an empty variable to store the return values of os.Create and os.Open. Code:

func main() {

  var path = "list.txt"
  // Some attempts:
  // var file File{}
  // var file *File

  // Check if file exists
  var _, err = os.Stat(path)

  // If new file, create it
  if os.IsNotExist(err) {
    var file, err = os.Create(path)

    // If file exists, open it
  } else {
    var file, err = os.Open(path)
  }

  // Check errors opening and creating file
  if err != nil {
    log.Fatal(err)
    return
  }

  // Defer closing file
  defer file.Close()

}

Both attempts result in the following error:

./main.go:13: undefined: File

I'm sure this is one of those things that I don't know I don't know. What I do know:

  • Per os/file.go, type of the return value I'm looking for is *File
  • That type is defined in os/file_unix.go as a struct

Can someone explain to me:

  1. How do I create an empty variable that can then be used to store the first variable in the results of os.Create and os.Open.
  2. Why were my two attempts wrong?
  3. Anything else that I'm misunderstanding.
  • 写回答

1条回答 默认 最新

  • dpecb06062 2017-07-09 21:35
    关注

    Defining variable is var <variable-name> <type>, learn more about variables.

    var file *os.File
    var err error
    

    Your updated code:

    func main() {
      path := "list.txt"
    
      var file *os.File
      var err error
    
      // Check if file exists
      if err = os.Stat(path); os.IsNotExist(err) {
        file, err = os.Create(path)
      } else { // If file exists, open it
        file, err = os.Open(path)
      }
    
      // Check errors opening and creating file
      if err != nil {
        log.Fatal(err)
        return
      }
    
      // Defer closing file
      defer file.Close()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染