1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Go]文字列結合してファイルパス作るときの話

Posted at

備忘録として

ベースとなるディレクトリパスを基準に、とあるファイルまでのパスを下のような感じで記述していた箇所があったが、「実行環境が Windows である可能性も考えて filepath.Join 使ってください」とレビューで指摘をいただいた。

sample.go
package main

import "fmt"

func main() {
	baseDir := "xxx/xxx"
	fileName := "sample.txt"
	filePath := baseDir + "/" + fileName

	fmt.Println(filePath)
}

…たしかになぁ! Windows だと区切りが \ になるしなぁ!

というわけで下のような形にしとくのが無難。

sample.go
package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	baseDir := filepath.Join("xxx", "xxx")
	fileName := "sample.txt"
	filePath := filepath.Join(baseDir, fileName)

	fmt.Println(filePath)
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?