수색…
세로보
fmt.Stringer
인터페이스에는 단일 메소드 인 String() string
이 필요합니다. 문자열 메소드는 해당 값에 대한 "원시"문자열 형식을 정의하며 값이 fmt
패키지 형식화 또는 인쇄 루틴 중 하나에 제공되면 기본 표현입니다.
package main
import (
"fmt"
)
type User struct {
Name string
Email string
}
// String satisfies the fmt.Stringer interface for the User type
func (u User) String() string {
return fmt.Sprintf("%s <%s>", u.Name, u.Email)
}
func main() {
u := User{
Name: "John Doe",
Email: "johndoe@example.com",
}
fmt.Println(u)
// output: John Doe <johndoe@example.com>
}
기본 fmt
패키지 fmt는 형식 verb를 사용하여 형식화 된 I / O를 구현합니다.
%v // the value in a default format
%T // a Go-syntax representation of the type of the value
%s // the uninterpreted bytes of the string or slice
형식 함수
fmt
에는 4 가지 주요 함수 유형이 있고 그 안에는 몇 가지 변형이 있습니다.
인쇄
fmt.Print("Hello World") // prints: Hello World
fmt.Println("Hello World") // prints: Hello World\n
fmt.Printf("Hello %s", "World") // prints: Hello World
스프린트
formattedString := fmt.Sprintf("%v %s", 2, "words") // returns string "2 words"
Fprint
byteCount, err := fmt.Fprint(w, "Hello World") // writes to io.Writer w
http
핸들러 내에서 Fprint
사용할 수 있습니다.
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello %s!", "Browser")
} // Writes: "Hello Browser!" onto http response
주사
스캔은 표준 입력에서 읽은 텍스트를 스캔합니다.
var s string
fmt.Scanln(&s) // pass pointer to buffer
// Scanln is similar to fmt.Scan(), but it stops scanning at new line.
fmt.Println(s) // whatever was inputted
스트링거 인터페이스
String()
메소드가있는 모든 값은 fmt
inteface Stringer
구현합니다.
type Stringer interface {
String() string
}
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow