golang笔记

获取命令行参数

命令行参数封装在os包内,使用os.Args得到命令行参数的数组

示例:

package main

import (
	"fmt"
	"os"
	"runtime"
)

func main() {

	var s, sep string
	/**
	一般的for语法
	**/
	for i := 1; i < len(os.Args); i++ {
		s += sep + os.Args[i]
		sep = " "
	}
	fmt.Println(runtime.GOOS)
	fmt.Println(s)
	/**
	for range 语法
	**/
	for _, arg := range os.Args[1:] {
		s += sep + arg
		sep = " "
	}
	fmt.Println(s)

	/**
	strings.Join()方法完成字符串拼接
	**/
	var s2 = strings.Join(os.Args[1:], " ")
	fmt.Println(s2)
}

备注:os.Args[0] = C:\Users\linji\AppData\Local\Temp\go-build361626070\b001\exe\echo1.exe

查找重复的行

示例:

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	counts := make(map[string]int)
	files := os.Args[1:]
	/**
	计算入参,如果入参为空,则监听输入流
	**/
	if len(files) == 0 {
		countLines(os.Stdin, counts)
	} else {
		for _, arg := range files {
			f, err := os.Open(arg)
			if err != nil {
				fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
				continue
			}
			countLines(f, counts)
			f.Close()
		}
	}
	for line, n := range counts {
		/**
		打印每一行的数量统计
		**/
		fmt.Printf("%d\t%s\n", n, line)
	}
}

func countLines(f *os.File, counts map[string]int) {
	input := bufio.NewScanner(f)
	for input.Scan() {
		counts[input.Text()]++
	}
}