在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的WriteString()函數用於將陳述的字符串“s”的內容寫入到寫入器“w”,該寫入器占用一個字節字節。如果“w”是由StringWriter實現的,則立即調用其WriteString方法。否則,w.Write隻會被調用一次。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。
用法:
func WriteString(w Writer, s string) (n int, err error)
在這裏,“w”是寫入器,而“s”是寫入寫入器的字符串。
返回值:它返回int類型的內容的字節總數,如果有的話,還返回錯誤。
以下示例說明了上述方法的使用:
範例1:
// Golang program to illustrate the usage of
// io.WriteString() function
// Including main package
package main
// Importing fmt, io, and os
import (
"fmt"
"io"
"os"
)
// Calling main
func main() {
// Defining w using Stdout
w:= os.Stdout
// Calling WriteString method with its parameters
n, err:= io.WriteString(w, "GfG\n")
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("n:%d\n", n)
}
輸出:
GfG n:4
範例2:
// Golang program to illustrate the usage of
// io.WriteString() function
// Including main package
package main
// Importing fmt, io, and os
import (
"fmt"
"io"
"os"
)
// Calling main
func main() {
// Defining w using Stdout
w:= os.Stdout
// Calling WriteString method with its parameters
n, err:= io.WriteString(w, "GeeksforGeeks\nis\na\nCS-Portal.\n")
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("n:%d\n", n)
}
輸出:
GeeksforGeeks is a CS-Portal. n:30
在此,在上麵的示例中,使用“Stdout”來創建默認文件描述符,並在其中寫入規定的內容。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 io.WriteString() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。