Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

golang 常用的代码片段 #16

Open
ToPeas opened this issue Oct 30, 2019 · 0 comments
Open

golang 常用的代码片段 #16

ToPeas opened this issue Oct 30, 2019 · 0 comments
Labels
go go语言

Comments

@ToPeas
Copy link
Owner

ToPeas commented Oct 30, 2019

读取文件放入切片里面

func readLines(path string) ([]string, int, error) {
  file, err := os.Open(path)
  if err != nil {
    return nil,0, err
  }
  defer file.Close()
  var lines []string
  lineCount :=0
  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    lines = append(lines, scanner.Text())
    lineCount++
  }
  return lines,lineCount,scanner.Err()
} 

使用bufio包的scanner可以对数据进行扫描输入,除了逐行分割以外,还有其他的分割方式:
ScanLines(默认)
ScanWords(分割单词)
ScanRunes(在遍历 UTF-8 字符串而不是字节时将会非常有用)
ScanBytes (用来找出 data 中的单个字节并返回)

@ToPeas ToPeas added the go go语言 label Oct 30, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
go go语言
Projects
None yet
Development

No branches or pull requests

1 participant