在Go語言中,fmt軟件包使用與C的printf()和scanf()函數相似的函數來實現格式化的I /O。 Go語言格式的fmt.Sprint()函數使用其操作數的默認格式,並返回結果字符串。當任何字符串不用作常量時,此處在操作數之間添加空格。此外,該函數在fmt包下定義。在這裏,您需要導入“fmt”包才能使用這些函數。
用法:
func Sprint(a ...interface{}) string
在此,“ a…interface {}”包含一些字符串,其中包括指定的常量變量。
返回值:它返回結果字符串。
範例1:
// Golang program to illustrate the usage of
// fmt.Sprint() function
// Including the main package
package main
// Importing fmt, io and os
import (
"fmt"
"io"
"os"
)
// Calling main
func main() {
// Declaring some const variables
const name, dept = "GeeksforGeeks", "CS"
// Calling Sprint() function
s:= fmt.Sprint(name, " is a ", dept, " Portal.\n")
// Calling WriteString() function to write the
// contents of the string "s" to "os.Stdout"
io.WriteString(os.Stdout, s)
}
輸出:
GeeksforGeeks is a CS Portal.
範例2:
// Golang program to illustrate the usage of
// fmt.Sprint() function
// Including the main package
package main
// Importing fmt, io and os
import (
"fmt"
"io"
"os"
)
// Calling main
func main() {
// Declaring some const variables
const num1, num2, num3 = 5, 10, 15
// Calling Sprint() function
s:= fmt.Sprint(num1, num2, num3)
// Calling WriteString() function to write the
// contents of the string "s" to "os.Stdout"
io.WriteString(os.Stdout, s)
}
輸出:
5 10 15
在上麵的代碼中,可以看出函數Sprint()沒有使用任何空格,但在數字之間的輸出中仍可以看到空格,這是因為函數本身添加了空格,因為沒有將單個字符串用作常量變量。
範例3:
// Golang program to illustrate the usage of
// fmt.Sprint() function
// Including the main package
package main
// Importing fmt, io and os
import (
"fmt"
"io"
"os"
)
// Calling main
func main() {
// Declaring some const variables
const str1, str2, str3 = "a", "b", "c"
// Calling Sprint() function
s:= fmt.Sprint(str1, str2, str3)
// Calling WriteString() function to write the
// contents of the string "s" to "os.Stdout"
io.WriteString(os.Stdout, s)
}
輸出:
abc
在上麵的代碼中,可以看出函數Sprint()沒有使用任何空格,並且在兩個字母之間的輸出中也看不到空格,這是因為常量變量中使用了字符串。
相關用法
- 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()用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 fmt.Sprint() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。