[pkg] ioutil
ioutil @ golang
寫檔 write file
// []byte 指的是 byte slice
// perm 指的是 permission,也就是誰可以讀取或寫入檔案
func WriteFile(filename string, data []byte, perm os.FileMode) error
err := ioutil.WriteFile(filename, bs, 0666)
Example 將 string slice 轉字串後,再轉成 byte 進行存檔
string slice —> string —> byte
package main
import (
"io/ioutil"
"strings"
)
// STEP 1: 定義 fruits type
type fruits []string
func main() {
favoriteFruits := fruits{"Apple", "Banana", "Orange", "Guava"}
favoriteFruits.saveToFile("fruits")
}
// STEP 2: 將 type fruits 轉成字串的 toString 的方法
func (f fruits) toString() string {
return strings.Join(f, ",")
}
// STEP 3: 將 type fruits 轉成 byte slice 並存檔的方式
func (f fruits) saveToFile(filename string) error {
s := f.toString()
bs := []byte(s) // 型別轉換:將字串轉換成 byte slice
return ioutil.WriteFile(filename, bs, 0666) // 0666 任何人都可以讀寫此檔案
}