Szukaj…


Podłużnica

Interfejs fmt.Stringer wymaga jednej metody String() string celu spełnienia fmt.Stringer . Metoda string definiuje „natywny” format ciągu dla tej wartości i jest domyślną reprezentacją, jeśli wartość jest dostarczana do dowolnego z procedur formatowania lub drukowania pakietów 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: "[email protected]",
    }

    fmt.Println(u)
    // output: John Doe <[email protected]>
}

Playground

Basic fmt

Pakiet fmt implementuje sformatowane operacje we / wy za pomocą czasowników formatujących:

%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

Funkcje formatowania

Istnieją 4 główne typy funkcji w fmt i kilka odmian w obrębie.

Wydrukować

fmt.Print("Hello World")        // prints: Hello World
fmt.Println("Hello World")      // prints: Hello World\n
fmt.Printf("Hello %s", "World") // prints: Hello World

Sprint

formattedString := fmt.Sprintf("%v %s", 2, "words") // returns string "2 words"

Fprint

byteCount, err := fmt.Fprint(w, "Hello World") // writes to io.Writer w

Fprint może być używany wewnątrz Fprint obsługi http :

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello %s!", "Browser")
}   // Writes: "Hello Browser!" onto http response

Skanowanie

Skanuj skanuje tekst odczytany ze standardowego wejścia.

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

Interfejs Stringer

Każda wartość, która ma metodę String() , implementuje interfejs fmt Stringer

type Stringer interface {
        String() string
}


Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow