認識 Go 標準輸出函式

函式

Print

函式 Print 將內容寫入至標準輸出。

1
func Print(a ...interface{}) (n int, err error)

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
)

func main() {
const name, age = "Kim", 22
fmt.Print(name, " is ", age, " years old.\n")

// It is conventional not to worry about any
// error returned by Print.
}

// Kim is 22 years old.

Printf

函式 Printf 將內容格式化寫入至標準輸出。

1
func Printf(format string, a ...interface{}) (n int, err error)

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
)

func main() {
const name, age = "Kim", 22
fmt.Printf("%s is %d years old.\n", name, age)

// It is conventional not to worry about any
// error returned by Printf.
}

// Kim is 22 years old.

Println

函式 Println 將內容寫入至標準輸出並換行。

1
func Println(a ...interface{}) (n int, err error)

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
)

func main() {
const name, age = "Kim", 22
fmt.Println(name, "is", age, "years old.")

// It is conventional not to worry about any
// error returned by Println.
}

// Kim is 22 years old.

Fprint

函式 Fprint 將內容寫入至實作 io.Writer 接口的變數:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"fmt"
"os"
)

func main() {
const name, age = "Kim", 22
n, err := fmt.Fprint(os.Stdout, name, " is ", age, " years old.\n")

// The n and err return values from Fprint are
// those returned by the underlying io.Writer.
if err != nil {
fmt.Fprintf(os.Stderr, "Fprint: %v\n", err)
}
fmt.Print(n, " bytes written.\n")
}

// Kim is 22 years old.
// 21 bytes written.

Fprintf

函式 Fprintf 將內容格式化寫入至實作 io.Writer 接口的變數:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"fmt"
"os"
)

func main() {
const name, age = "Kim", 22
n, err := fmt.Fprintf(os.Stdout, "%s is %d years old.\n", name, age)

// The n and err return values from Fprintf are
// those returned by the underlying io.Writer.
if err != nil {
fmt.Fprintf(os.Stderr, "Fprintf: %v\n", err)
}
fmt.Printf("%d bytes written.\n", n)
}

// Kim is 22 years old.
// 21 bytes written.

Fprintln

函式 Fprintln 將內容寫入至實作 io.Writer 接口的變數並換行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"fmt"
"os"
)

func main() {
const name, age = "Kim", 22
n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.")

// The n and err return values from Fprintln are
// those returned by the underlying io.Writer.
if err != nil {
fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err)
}
fmt.Println(n, "bytes written.")
}

// Kim is 22 years old.
// 21 bytes written.

參考資料