이것은 Mark Summerfield에서의 프로그래밍의 예입니다.Go to FilePaths
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
var britishAmerican = "british-american.txt"
func init() {
dir, _ := filepath.Split(os.Args[0])
britishAmerican = filepath.Join(dir, britishAmerican)
}
func main() {
rawBytes, err := ioutil.ReadFile(britishAmerican)
if err != nil {
fmt.Println(err)
}
text := string(rawBytes)
usForBritish := make(map[string]string)
lines := strings.Split(text, "\n")
fmt.Println(lines)
for _, line := range lines {
fields := strings.Fields(line)
if len(fields) == 2 {
usForBritish[fields[0]] = fields[1]
}
}
fmt.Println(usForBritish)
}
이 코드를 주석으로 실행하면, 완벽하게 정상적으로 작동합니다.
open /var/folders/l6/rdqtyrfd303dw1cz8qvlfcvc0000gn/T/go- build652175567/command-line-arguments/_obj/exe/british-american.txt: no such file or directory exit status 1
내 질문은, 왜 init()
가 해당 디렉토리에서 파일을 잡아되지 FUNC 않습니다한다 : 나는 그것을 떠날 경우이 오류가?
이 코드에서'go fmt'를 실행하면 읽는 것이 더 쉬울 것입니다. [놀이터] (https://play.golang.org/)에서도이 작업을 수행 할 수 있습니다. - 또한 MCVE (https://stackoverflow.com/help/mcve 참조)를 만드는 데 도움이됩니다. – topskip
포맷 오류로 불편을 끼쳐 드려 죄송합니다. 여기 놀이터에 있습니다 https://play.golang.org/p/G8cUb6fZC9 – Deliri
게시물을 편집하면 독자가 쉽게 읽을 수 있습니다 (링크를 따를 필요가 없습니다) – topskip