golang os.Create导致“没有这样的文件或目录”错误

Must be something simple, but I cannot seem to figure out. I keep getting "no such file or directory" error. Thought the Create function is to create a new file? package main

import (
  "log"
  "os"
)

func main() {
  f, err := os.Create("~/golang-server.log")
  defer f.Close()
  if err != nil {
    panic(err.Error())
  }
  log.SetOutput(f)
}

You can't use ~ or environment variable like $HOME to specify the file path, they're string literal and means actual path. The error you got is because it treat ~/golang-server.log as a relative path of current directory, and there's no directory ~ in current directory.

With manually created sub-directory ~, your code will succeed:

 ~/test/ mkdir \~
 ~/test/ go run t.go
 ~/test/ ls \~
golang-server.log

So need to pass an absolute path or relative path to os.Create.