Skip to content

Latest commit

 

History

History
71 lines (60 loc) · 1.21 KB

5.md

File metadata and controls

71 lines (60 loc) · 1.21 KB

循环语句

for

  • for的条件里不需要括号
  • for的条件里可以省略初始条件、结束条件以及递增表达式
package main
import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strconv"
    "strings"
)

func convertToBin(n int) string {
    result := ""
    for ; n > 0; n /= 2 {
        lsb := n % 2
        result = strconv.Itoa(lsb) + result
    }
    return result
}

func printFile(filename string) {
    file, err := os.Open(filename)
    if err != nil {
        panic(err)
    }

    printFileContents(file)
}

func printFileContents(reader io.Reader) {
    scanner := bufio.NewScanner(reader)

    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
}

func forever() {
    for {
        fmt.Println("abc")
    }
}

func main() {
    fmt.Println("convertToBin results:")
    fmt.Println(
        convertToBin(5),  // 101
        convertToBin(13), // 1101
        convertToBin(72387885),
        convertToBin(0),
    )

    fmt.Println("abc.txt contents:")
    printFile("basic/branch/abc.txt")

    fmt.Println("printing a string:")
    s := `abc"d"
    kkkk
    123

    p`
    printFileContents(strings.NewReader(s))

    // Uncomment to see it runs forever
    // forever()
}