Friday, 17 July 2020

Working with strings in Go

Strings are implemented as a reference type, though they're immutable.


s := "This is in first line"
s += "\n"
s += "...and this is in the second line"

How do you write multiline strings in Go?

This raw quote (raw literal) does not parse escape sequences (\n would remain):

`line 1
line 2\n
line 3`

It is possible to use formatters though:

fmt.Sprintf(`a = %d`, 123)

Another option:

"line 1" +
"line 2" +
"line 3"

What is the difference between backticks (``) & double quotes (“”) in golang?

String Comparison - use == or !=

Slice string into letters

String Formatting 

s := fmt.Sprintf("a %s", "string")

Go by Example: String Formatting
Extracting substrings in Go

%x - formats value as HEX string with lowercase letters
%X - formats value as HEX string with uppercase letters

var n []byte = ...
s := fmt.Sprinf("%x", n) 

How to print struct variables in console? To print the name of the fields in a struct:

fmt.Printf("%+v\n", myStruct)

To convert string to byte array use:

s string
buffer := []byte(s)


fmt.Println("Table names:", tableNames)

SPACE character is automatically inserted between these two strings.

Golang - How to print the values of Arrays?

fmt.Printf("%v", projects)


%+v - prints struct’s field names (if value is a struct)

Go string = byte sequence, UTF-8 encoded
Unicode UTF-8 code point = 1-4 bytes (1 for ASCII)
rune = int32 => can store each UTF-8 code point 

Unicode string example: en dash & Chinese letter 

package main

import (

func main() {
s := "\u2013汉"
fmt.Printf("Character %s has %d bytes, %d UTF-8 code points", s, len(s), len([]rune(s)))


Character –汉 has 6 bytes, 2 UTF-8 code points

1 comment:

micheal pan said...

BE SMART AND BECOME RICH IN LESS THAN 3DAYS....It all depends on how fast 
you can be to get the new PROGRAMMED blank ATM card that is capable of
hacking into any ATM machine,anywhere in the world. I got to know about 
this BLANK ATM CARD when I was searching for job online about a month 
ago..It has really changed my life for good and now I can say I'm rich and 
I can never be poor again. The least money I get in a day with it is about 
$50,000.(fifty thousand USD) Every now and then I keeping pumping money 
into my account. Though is illegal,there is no risk of being caught 
,because it has been programmed in such a way that it is not traceable,it 
also has a technique that makes it impossible for the CCTVs to detect 
you..For details on how to get yours today, email the hackers on : ( ). Tell your 
loved once too, and start to live large. That's the simple testimony of how 
my life changed for good...Love you all ...the email address again is ;