মূল কন্টেন্টে যান
eLearner.app
মডিউল 1 · 5-এর পাঠ 5কোর্সে 5/50~10 min
মডিউল পাঠ (5/5)

fmt সহ ইনপুট/আউটপুট

The standard library's fmt package is your main tool for printing to the console, formatting strings and reading input. If you have used printf in C you'll feel right at home, but with some extra refinement thanks to the %v and %T verbs.

Print, Println, Printf: three functions, three behaviors

Go
fmt.Print("ciao ", "mondo")    // "ciao mondo"  (niente newline finale)
fmt.Println("ciao", "mondo")   // "ciao mondo\n" (newline + spazi tra argomenti)
fmt.Printf("eta=%d\n", 36)     // "eta=36\n"    (format string esplicita)

The verbs you'll use all the time

VerbWhat it printsExample
%v"default value" — works on any type{Ada 36}
%+vlike %v but with field names in structs{Name:Ada Age:36}
%#v"Go-syntax" representation of the valuemain.User{Name:"Ada", Age:36}
%Tthe type of the valuefloat64
%dinteger in base 1042
%ffloat3.140000
%.2ffloat with 2 decimals3.14
%sstringAda
%q"quoted" string (with quotes and escapes)"Ada\n"
%tbooltrue
%xhexadecimal (lowercase)2a
%bbinary101010
Go
u := struct{ Name string; Age int }{"Ada", 36}
fmt.Printf("%v\n", u)   // {Ada 36}
fmt.Printf("%+v\n", u)  // {Name:Ada Age:36}
fmt.Printf("%T\n", 3.14) // float64

Sprintf: building strings without printing them

Same interface as Printf, but the result is returned to you as a string:

Go
msg := fmt.Sprintf("L'utente %s ha %d anni", "Ada", 36)
fmt.Println(msg) // L'utente Ada ha 36 anni

You'll use it constantly to build messages, logs and errors.

Errorf: strings + error wrapping

fmt.Errorf creates an error with Printf-style formatting. With the special verb %w you can wrap an existing error to preserve its chain (we'll cover this in depth in the Interfaces module):

Go
if _, err := os.Open("missing"); err != nil {
    return fmt.Errorf("apertura config: %w", err)
}

Your turn

ব্যায়াম#go.m1.l5.e1
প্রচেষ্টা: 0লোড হচ্ছে...

Print the string 'ciao mondo' using fmt.Println.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

`fmt.Println` takes a string and adds the newline itself.

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

ব্যায়াম#go.m1.l5.e2
প্রচেষ্টা: 0লোড হচ্ছে...

Use fmt.Printf to print 'eta=36' followed by a newline, using the %d verb for the integer.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

`Printf` doesn't add a newline: you have to include `\\n` in the format string.

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

Quiz#go.m1.l5.e3
প্রস্তুত

Which verb prints the dynamic TYPE of a value?

Go
fmt.Printf("?\n", 3.14)
উত্তরের বিকল্প

Recap

  • Print/Println/Printf differ in spaces and newlines.
  • %v is the wildcard that works on any type; %+v shows field names.
  • %T prints the type (useful for quick debugging).
  • Sprintf builds strings; Errorf builds errors with wrapping (%w).
  • Printf does NOT add a newline: write it yourself in the format string.