What is the correct string format specifier for integer in fmt.Printf? - go

var count int = 5
fmt.Printf("count:%i\n", count)
Its output is
count:%!i(int=5)
What is the correct format specifier so that the output is
count:5
I look up the package fmt's method Printf in Go's package website, but it doesn't say about the syntax for a format specifier. Where can I find the syntax?
Thanks.

%d is the format specifier for base 10 integers (what you typically want) a full listing of fmt's format specifiers can be found here; https://golang.org/pkg/fmt/
var count int = 5
fmt.Printf("count:%d\n", count)
// prints count:5

%d is the format specifier for integer. However, You can use %v to print the value of the variable in default format, no matter what the data type is.
For example:
package main
import (
"fmt"
)
func main() {
//prints Hello 1 0.5 {Hello}
fmt.Printf("%v %v %v %v", "Hello", 1, 0.5, struct{ v string }{"Hello"})
}

You could also simply opt for the Println function:
fmt.Println("count:", count)

Related

html/template is not showing a float value with e+07 notation in exact decimal places

I'm trying an example where I'm passing a value 1.8e+07 to the TestVal field of struct Student. Now I want this 1.8e+07 value to be in exact decimal places but it is not doing so. It is able to show the value in exact decimal places(180000) if the value is 1.8e+05. But if it is greater than e+05 then it is unable to show it.
Example
package main
import (
"fmt"
"os"
"text/template"
)
// declaring a struct
type Student struct {
Name string
TestVal float32
}
// main function
func main() {
std1 := Student{"AJ", 1.8e+07}
// "Parse" parses a string into a template
tmp1 := template.Must(template.New("Template_1").Parse("Hello {{.Name}}, value is {{.TestVal}}"))
// standard output to print merged data
err := tmp1.Execute(os.Stdout, std1)
// if there is no error,
// prints the output
if err != nil {
fmt.Println(err)
}
}
Please help.
That's just the default formatting for floating point numbers. The package doc of fmt explains it: The %v verb is the default format, which for floating numbers means / reverts to %g which is
%e for large exponents, %f otherwise. Precision is discussed below.
If you don't want the default formatting, use the printf template function and specify the format you want, for example:
{{printf "%f" .TestVal}}
This will output (try it on the Go Playground):
Hello AJ, value is 18000000.000000
Or use:
{{printf "%.0f" .TestVal}}
Which will output (try it on the Go Playground):
Hello AJ, value is 18000000
See related:
Format float in golang html/template

How do Print and Printf differ from each other in Go?

I am new to Go and understanding simple syntax and functions. Here I am confused between Print and Printf function. The output of those function is similar, so what is the difference between these two functions?
package main
import (
"fmt"
"bufio"
"os"
)
func main(){
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Text: ")
str, _ := reader.ReadString('\n')
fmt.Printf(str)
fmt.Print(str)
}
I read https://golang.org/pkg/fmt/#Print to understand, but I did not understand it.
From the docs about Printing:
For each Printf-like function, there is also a Print function that takes no format and is equivalent to saying %v for every operand. Another variant Println inserts blanks between operands and appends a newline.
So Printf takes a format string, letting you tell the compiler what format to output your variables with and put them into a string with other information, whereas Print just outputs the variables as they are. Generally you'd prefer to use fmt.Printf, unless you're just debugging and want a quick output of some variables.
In your example you're sending the string you want to print as the format string by mistake, which will work, but is not the intended use. If you just want to print one variable in its default format it's fine to use Print.
Printf method accepts a formatted string for that the codes like "%s" and "%d" in this string to indicate insertion points for values. Those values are then passed as arguments.
Example:
package main
import (
"fmt"
)
var(
a = 654
b = false
c = 2.651
d = 4 + 1i
e = "Australia"
f = 15.2 * 4525.321
)
func main(){
fmt.Printf("d for Integer: %d\n", a)
fmt.Printf("6d for Integer: %6d\n", a)
fmt.Printf("t for Boolean: %t\n", b)
fmt.Printf("g for Float: %g\n", c)
fmt.Printf("e for Scientific Notation: %e\n", d)
fmt.Printf("E for Scientific Notation: %E\n", d)
fmt.Printf("s for String: %s\n", e)
fmt.Printf("G for Complex: %G\n", f)
fmt.Printf("15s String: %15s\n", e)
fmt.Printf("-10s String: %-10s\n",e)
t:= fmt.Sprintf("Print from right: %[3]d %[2]d %[1]d\n", 11, 22, 33)
fmt.Println(t)
}
As per docs
Print: will print number variables, and will not include a line break at the end.
Printf: will not print number variables, and will not include a line break at the end.
Printf is for printing formatted strings. And it can lead to more readable printing.
For more detail visit this tutorial.

Return all contents within an object

I am very new to Go, so I am sorry for that noob question.
In JavaScript console.log(window) returns all objects inside of window. In PHP var_dump(new DateTime()) returns all objects inside of DateTime().
Is there a function in Go that will return all objects from a given object? For example Println should be returned if fmt is given.
Try executing go doc fmt in a terminal to produce a description of the "fmt" package and a listing of the functions it exports, or referring to the fmt package documentation at https://golang.org. In go, as in most other static/compiled languages, users are expected to refer to documentation (or docs) which describe the programming language and its libraries. Contrast this to some dynamic/scripting languages, which often make it easy to query any object to discover its usable properties.
At runtime, you can get a helpful printout of any arbitrary value by using the %#v formatting verb to produce a go syntax representation of the value, e.g.
xs := []int{1, 2, 3}
fmt.Printf("OK: xs=%#v\n", xs)
// OK: xs=[]int{1, 2, 3}
Note that the package "fmt" is not a value in the go language so it cannot be printed at runtime as such.
In Go is possible does something similar, but don't work for all.
func main() {
//arrays
a := []int{1,2,3,4}
fmt.Printf("%v\r\n", a) //print [1 2 3 4]
//maps
b := map[string]int{
"a":1,
"b":2,
}
fmt.Printf("%v\r\n", b) //print map[a:1 b:2]
//structs
c := struct{
A int
B int
}{1,2}
d := struct{
C struct{
A int
B int
}
D int
}{c,2}
fmt.Printf("%v\r\n", d) //print {{1 2} 2}
}
See in: https://play.golang.org/p/vzlCsOG497h
If you pass fmt occurs error because it is a package. The error is:
Error: use of package fmt without selector
I hope this helps (too)!
GO OOP, & inheritance
Go does not have objects, but we do have custom types and interfaces that we can attach attributes, functions and other types to.
What specifically are you trying to do? If you're looking for a var_dump:
USING fmt.Println
someErr := fmt.Errorf("custom type error")
fmt.Println(someErr)
Println formats using the default formats for its operands and writes to standard output.
USING fmt.Printf
someErr := fmt.Errorf("custom type error")
fmt.Printf("This is an error:%v A num: %v A str", someErr, 19, "Stackoverflow")
Printf formats according to a format specifier and writes to standard output.
USING fmt.Sprintf
someErr := fmt.Errorf("custom type error")
// someStr now contains the string formatted as shown below
someStr := fmt.Sprintf("This is an error:%v A num: %v A str", someErr, 19, "Stackoverflow")
Sprintf formats according to a format specifier and returns the resulting string.
Here is an example of my personal preference when outputting var data:
https://play.golang.org/p/8dpeE-fray_J
I hope this helps!

What is "%!s" in the output of a float?

I'm getting coordinates (location) as an output of 2 float64 numbers, and it looks like this:
&{%!s(float64=42.539679) %!s(float64=42.601339)}
This is the first time I'm seeing anything like that, so what is "%!s"?
"TypeOf" says "%!s(float64=42.539679)" is float64. So how do I work with this kind of floats? Is there any way to parse it, or somehow to make the %!s(float64=42.539679) look like 42.539679?
UPD: the highlighted line is a *tgbotapi.Location object from Syfaro's telegram bot api.
The api has this structure:
type Location struct {
Longitude float64 `json:"longitude"`
Latitude float64 `json:"latitude"`
}
and the Location.Latitude gives me this: "%!s(float64=42.539679)" (float64)(?)
https://golang.org/pkg/fmt/
%!s is basically used in errors to help you identify a problem.
I think this is a matter of using an incorrect format "verb." You need to use %f instead of %s
package main
import (
"fmt"
)
func main() {
var f float64 = 3.14
fmt.Printf("attempting to print as string: %s \n", f)
fmt.Printf("attempting to print as float: %f", f)
}
Runnable: https://play.golang.org/p/Pec_QrxBIl

How to convert uint8 to string

I want to convert uint8 to string but can't figure out how.
package main
import "fmt"
import "strconv"
func main() {
str := "Hello"
fmt.Println(str[1]) // 101
fmt.Println(strconv.Itoa(str[1]))
}
Example
This gives me prog.go:11: cannot use str[1] (type uint8) as type int in function argument [process exited with non-zero status]
Any idea?
Simply convert it :
fmt.Println(strconv.Itoa(int(str[1])))
There is a difference between converting it or casting it, consider:
var s uint8 = 10
fmt.Print(string(s))
fmt.Print(strconv.Itoa(int(s)))
The string cast prints '\n' (newline), the string conversion prints "10". The difference becomes clear once you regard the []byte conversion of both variants:
[]byte(string(s)) == [10] // the single character represented by 10
[]byte(strconv.Itoa(int(s))) == [49, 48] // character encoding for '1' and '0'
see this code in play.golang.org
You can do it even simpler by using casting, this worked for me:
var c uint8
c = 't'
fmt.Printf(string(c))
There are no automatic conversions of basic types in Go expressions. See https://talks.golang.org/2012/goforc.slide#18. A byte (an alias of uint8) or []byte ([]uint8) has to be set to a bool, number or string.
package main
import (
. "fmt"
)
func main() {
b := []byte{'G', 'o'}
c := []interface{}{b[0], float64(b[0]), int(b[0]), rune(b[0]), string(b[0]), Sprintf("%s", b), b[0] != 0}
checkType(c)
}
func checkType(s []interface{}) {
for k, _ := range s {
// uint8 71, float64 71, int 71, int32 71, string G, string Go, bool true
Printf("%T %v\n", s[k], s[k])
}
}
Sprintf("%s", b) can be used to convert []byte{'G', 'o' } to the string "Go". You can convert any int type to a string with Sprintf. See https://stackoverflow.com/a/41074199/12817546.
But Sprintf uses reflection. See the comment in https://stackoverflow.com/a/22626531/12817546. Using Itoa (Integer to ASCII) is faster. See #DenysSéguret and https://stackoverflow.com/a/38077508/12817546. Quotes edited.
use %c
str := "Hello"
fmt.Println(str[1]) // 101
fmt.Printf("%c\n", str[1])

Resources