Golang Converting struct to string

eye-catch Golang

Converting to string type is often used but you don’t know how to do it? Let’s learn it together.

Sponsored links

Convert another type to string

It often needs to be done to convert a non-string type to string. Let’s check how to do it.

Int to string

You might have this experience. The conversion can be done by string(intValue) but it is converted to ASCII code.

intValue := 99
intStr1 := string(intValue)
fmt.Printf("intStr1: %s\n", intStr1) // c

If you want to check the table, go to this web site.

In most cases, this is not the expected result. We should use fmt.Sprint() function instead.

intStr2 := fmt.Sprint(intValue)
fmt.Printf("intStr2: %s\n", intStr2) // 99

This is what we actually want.

Float to string

If you try to convert float value to string by string(), you get an error.

floatValue := 12.345
floatStr := string(floatValue)
// cannot convert floatValue (variable of type float64) to string

However, fmt.Sprint() function can be used for float value too.

floatValue := 12.345
floatStr := fmt.Sprint(floatValue)
fmt.Printf("floatStr: %s\n", floatStr) // 12.345

Array to string

Likewise, use fmt.Sprint().

arrayValue := [5]int{1, 2, 3, 4, 5}
arrayStr := fmt.Sprint(arrayValue)
fmt.Printf("arrayValue: %s\n", arrayStr) // arrayValue: [1 2 3 4 5]

Byte to string

We can use the same functions here but it depends on your expected result which function to use.

rawBytes := []byte{48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58}
fmt.Printf("%s\n", rawBytes) // 0123456789

fmt.Printf("%s\n", string(rawBytes)) // 0123456789
fmt.Printf("%s\n", bytes.NewBuffer(rawBytes).String()) // 0123456789

If you want to use it as a human readable string, the two functions above can be used.

If you need the raw byte codes, use fmt.Sprint().

rawByteString := fmt.Sprint(rawBytes)
fmt.Printf("%s\n", rawByteString)    // [48 49 50 51 52 53 54 55 56 57 58]

Struct to string

Do you need struct too for … maybe logging? OK, let’s try.

type myStruct struct {
    name string
    age  uint64
}

myStruct := myStruct{name: "Yuto", age: 35}
fmt.Printf("%%v: %v\n", myStruct)   // %v: {Yuto 35}
fmt.Printf("%%T: %T\n", myStruct)   // %T: utils.myStruct
fmt.Printf("%%#v: %#v\n", myStruct) // %#v: utils.myStruct{name:"Yuto", age:0x23}
fmt.Println(myStruct) // {Yuto 35}

Hmm… None of them doesn’t return our expected result. %#v is nearly what we want but the int value is written as HEX.

But… official site describes about %+v.

%v the value in a default format
when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value
%T a Go-syntax representation of the type of the value
%% a literal percent sign; consumes no value
https://pkg.go.dev/fmt

https://pkg.go.dev/fmt

It works.

fmt.Printf("%%+v: %+v\n", myStruct)   // %+v: {name:Yuto age:35}

Then, let’s use fmt.Sprintf() function instead of fmt.Sprint().

struct_v := fmt.Sprintf("%+v", myStruct)
fmt.Println(struct_v) // {name:Yuto age:35}

There is another way if you want to make it more readable. The way is however to define it yourself.

func (m myStruct) String() string {
    return fmt.Sprintf("{ name: %s, age: %d }", m.name, m.age)
}

structStr := fmt.Sprint(myStruct)
fmt.Println(structStr) // { name: Yuto, age: 35 }

The String() is defined in the following way in fmt package.

type Stringer interface {
    String() string
}

This method is called in the case where the string conversion is needed.

Sponsored links

Extract specified ranged string by using slice

If you need to extract string in a certain range from the existing string, you can use slice.

numberStr := "0123456789"
slices := numberStr[2:8]
fmt.Println(slices) // 234567

Other data type conversions

Comments

  1. bbe
    Regarding the custom String() method, do you usually prefer implementing fmt.Stringer for debugging purposes, or do you lean more towards JSON marshaling when the struct gets too complex?

  2. Lip cream menjadi salah satu produk makeup yang praktis untuk melengkapi penampilan sehari-hari. Selain memberikan warna pada bibir, formula yang nyaman juga penting agar produk tetap terasa ringan ketika digunakan dalam waktu lama. Salah satu pilihan yang menarik adalah Hanasui Matcha Latte Edition Lip Cream Velvet Matte Moisturizing Dengan Olive Oil Dan Vitamin E.

    Memiliki tampilan bibir matte tidak selalu berarti harus menggunakan produk dengan hasil akhir yang terasa kering. Lip cream dengan formula moisturizing dapat menjadi pilihan bagi pengguna yang menginginkan warna intens sekaligus sensasi pemakaian yang lebih nyaman. Konsep inilah yang ditawarkan melalui Hanasui Matcha Latte Edition.

    Tekstur velvet matte memberikan hasil akhir yang lembut dan tidak terlalu kaku di bibir. Karakter tersebut membuat lip cream lebih mudah digunakan untuk berbagai kesempatan, baik ketika bekerja, kuliah, menghadiri acara santai, maupun sekadar melengkapi makeup harian.

    Kandungan olive oil dan vitamin E menjadi salah satu daya tarik dari produk ini. Keduanya dikenal luas dalam produk perawatan dan kosmetik karena dapat membantu menjaga kelembapan kulit. Pada lip cream, komponen tersebut memberikan nilai tambah bagi pengguna yang tetap memperhatikan kenyamanan bibir saat memakai makeup.

    Konsep Matcha Latte Edition juga memberikan kesan yang unik dan kekinian. Produk dengan tema tersebut cocok bagi pengguna yang menyukai kosmetik dengan tampilan menarik sekaligus mudah dimasukkan ke dalam pouch makeup. Ukurannya yang praktis memungkinkan lip cream dibawa untuk touch-up kapan saja.

    Penggunaan lip cream juga cukup fleksibel. Warna dapat diaplikasikan langsung pada seluruh permukaan bibir untuk tampilan lebih tegas atau dibuat tipis untuk menghasilkan kesan natural. Teknik tersebut memungkinkan satu produk digunakan untuk berbagai gaya makeup sesuai kebutuhan.

    Sebelum menggunakan produk kosmetik, pastikan kondisi bibir dalam keadaan bersih dan gunakan sesuai petunjuk pada kemasan. Setiap orang juga dapat memiliki respons berbeda terhadap bahan kosmetik, sehingga memperhatikan kecocokan produk tetap penting.

    Dengan perpaduan velvet matte, formula moisturizing, olive oil, dan vitamin E, Hanasui Matcha Latte Edition Lip Cream Velvet Matte Moisturizing Dengan Olive Oil Dan Vitamin E menjadi pilihan menarik bagi pengguna yang ingin mendapatkan warna bibir cantik dengan tampilan matte yang tetap nyaman untuk menunjang aktivitas sehari-hari.

Copied title and URL