Created
November 1, 2018 23:58
-
-
Save akolybelnikov/674941d1e12b5efd76e207cf786b0496 to your computer and use it in GitHub Desktop.
Read file and make structs of lines in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"log" | |
"os" | |
"strings" | |
) | |
// Name struct with two fields | |
type Name struct { | |
fname string | |
lname string | |
} | |
func main() { | |
names := make([]Name, 0) | |
fmt.Println("File name?") | |
var fileName string | |
fmt.Scan(&fileName) | |
f, err := os.Open(fileName) | |
if err != nil { | |
log.Fatalf("open file error: %v", err) | |
return | |
} | |
defer f.Close() | |
scanner := bufio.NewScanner(f) | |
for scanner.Scan() { | |
line := string(scanner.Text()) | |
splitLine := strings.Split(line, " ") | |
name := Name{fname: splitLine[0], lname: splitLine[1]} | |
names = append(names, name) | |
} | |
if err := scanner.Err(); err != nil { | |
log.Fatalf("scan file error: %v", err) | |
return | |
} | |
for i := 0; i < len(names); i++ { | |
fmt.Println(names[i].fname, names[i].lname) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment