Showing posts with label Beginner. Show all posts
Showing posts with label Beginner. Show all posts

Tuesday, March 2, 2021

Pointers in Go

Understand all about declaring and using pointers in Go

If you're coming from Python, Java, JavaScript, C# and others, talking pointers may scare you. But fear not! Go's approach to pointers is very elegant and definitely very easy to understand.

Variables

We cannot talk pointers without understanding variables. Every variable you declare in Go (or any programming language for that matter) is essentially a way to identify a block of memory that contains a value assigned to it.

There are multiple ways to declare variables in Go. For example:

package main

import "fmt"

func main() {
     var name = "John Smith"
     var email string = "john@smith.com"
     fmt.Printf("Name: %v, Email: %v", name, email)
}

We could have used the & operator to access the memory addresses of our variables:

fmt.Printf("&name: %v, &email: %v", &name, &email)
&name: 0xc00010a040, &email: 0xc00010a050

Pointers

But what about pointers? Pointers are nothing more than variables that hold the memory address of a value. In other words, the location at which a value is stored. In Go, the * character is used to either declare and read the value of a pointer For example, The type *T is a pointer to a T value.

The zero value for an unassigned pointer is always nil.

Declaring Pointers

To declare pointers, use the * character preceding its type. Like variables pointers have to be declared before they are accessed following this syntax:

var myVar *type

For example:

var p *int // declares a pointer to int

Assigning values to pointers

To assign values to pointers, you should point it to the address of another variable. That's done by using the & operator we saw previously:

i := 22 // assigns 22 to i (i is an int)
p = &i  // makes p point to the address of i

Reading pointer values

To read the values of our pointers we use the * operator:

fmt.Println(*p) // read i through the pointer p
What you see above is called "dereferencing" or "indirecting".

Nil Pointers

Since in Go you cannot declare and set a value to pointers, by default, every unassigned pointer has its zero values set to nil. The nil pointer is a constant with a value of zero as we can see in the example below:

q *int
fmt.Printf("Q: %v %x", q, q)
Q: <nil> 0

But what happens if we try to access its value before we use it? Yes, an error:

fmt.Println("Q: %v", *q)

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4990a3]

Checking if a pointer is assigned

To check if a pointer has been assigned to, you could compare it to nil. True means your pointer is assigned to a memory address and it's safe to access its value:

fmt.Println("Is p assigned?", p != nil)
Is p assigned? true

Comparing pointers

Can we compare pointers? Definitely, by using the & operator:

var x, y int
fmt.Println(&x == &x, &x == &y, &x == nil)
true false false

When use Pointers

So when should you use pointers? Since pointers allow accessing variables indirectly you may think that whenever you need to access your values. But the rule of thumb is that you should use pointers for sharing data - whenever you want an external function to be able to modify your data.

Limitations of Pointers

If you're coming from C, there's one important detail. Go unlike C, Go has no pointer arithmetic. 

Conclusion

On this post we learned about pointers in Go. If you're coming from Python, Java, JavaScript, C# and others, talking pointers may scare you. but fear not! Go's approach to pointers is very elegant and definitely very easy to understand.

Remember, that pointers make your code a little less legible so use them whenever you need to share some value.

See Also

Tuesday, February 2, 2021

Raw String Literals in Go

Learn what are Raw String Literals in Go and how to use them

On a previous posts we discussed Runes, Variables and Strings in Go. Today, let's continue our study of Go Strings by learning about raw string literals.

    Raw String Literals

    Raw string literals are character sequences between back quotes, as in `foo`. Within raw string literals, no escape sequences are processed; the contents are taken literally. For example:

    s := `{
    "name": "john"
    }`
    fmt.Println(s)

    Prints:

    {
    "name": "john"
    }

    Particularities of raw string literals

    Here are a few particularities of raw string literals:

    • within the quotes any character can appear except from back quote (`)
    • the value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes
    • the string may contain newlines
    • carriage return characters ('\r') are discarded
    • no escape sequences are processed; the contents are taken literally
    • a raw string literal may spread over several lines in the source code

    When to use raw string literals

    Due to its preservation of  format and disabled escaping nature, raw string literals are convenient in multiple contexts, including:

    • writing regular expressions
    • HTML templates
    • JSON literals
    • command usage messages
    • XML
    • YAML
    • and other formats that require preservation of the formatting
    We'll see uses of raw string literals for each of the above cases. Keep tuned!

    Conclusion

    On this post we learned a little more about Strings in Go by reviewing raw string literals. Since manipulating Strings is an essential part of a programmer's life, understanding their particularities is important to master the Go programming language.

      Source

      See Also

      Tuesday, January 26, 2021

      Strings in Go

      Learn the most important aspects of Strings in Go

      On a previous posts we discussed Runes and Variables. Today, let's continue our study of Go's basic types by learning more about Strings in Go. Since Strings in Go as not as obvious as in your favorite programming language, we recommend to explore this article at your own pace.

      Declaring Strings in Go

      You probably know how to declare variables in Go. Declaring strings is as simple as:

      s := "Hello Gopher" // or...
      var s2 string

      A string value can be written as a string literal, a sequence of bytes enclosed in double quotes. Strings in Go can also contain UTF characters:

      s2 := "Hello 😀"

      We can also treat Strings as arrays to access parts of it. For example:

      fmt.Println(s[:5]) // "Hello"
      fmt.Println(s[:])  // "Gopher"
      fmt.Println(s[:])  // "Hello Gopher"

      Concatenating Strings

      Concatenating Strings in Go is similar to Java, JavaScript and Python as Go also utilizes the + operator:
      s3 := "Goodbye,  " + s[5:] // "Goodbye, Gopher"
      String concatenation is an expensive operation. Avoid using it in loops as it will impact the performance of your application.

      Comparing Strings

      Strings may be compared with operators like == and <. And since the comparison is done byte by byte, the result is a sweet natural lexicographic ordering:  

      name1 := "john"
      name2 := "smith"
      fmt.Println(name1 == name2) // false
      fmt.Println(name1 > name2)  // false

      Substrings

      Go also allows easy access to access parts of your string. For example:

      s[3] - returns the value located on the 3rd position the array
      s[5:] - returns a substring from position 5 until the end
      s[:5] - returns a substring from position 0 to 5
      s[2:5] - returns a substring from position 2 to 5

      String Length

      If you thought that Go's built-in len function returns the length of a string, you're incorrect. As per the official documentation, len over strings returns the number of bytes in the string (not the number of characters). So if your variable contained any UTF-8 character, it would fail. For example:

      s := "Hello, 😊"
      fmt.Println(len(s)) // returns 11. Did you expect 8?

      To solve the above problem, we should resort to the package encoding/utf8:

      s := "Hello, 😊"
      fmt.Println(utf8.RuneCountInString(s)) // yes! now we have an 8!

      Loops over Strings

      As per the above, loops over strings should use range instead of len. Example:

      // incorrect as it fails for UTF-8 strings
      for i := 0; i < len(s); i++ {
          fmt.Printf("%d %q\n", i, s[i])
      }

      // correct
      for i, r := range s {
          fmt.Printf("%d\t%q\t%d\n", i, r, r)
      }

      Immutability

      Another important concept of Strings in Go is that they are immutable. By that, it means that once assigned, the byte sequence contained in a string value cannot be changed:

      s[7] = 'a'   // compiler error: cannot assign to s[7]

      But, as expected, a string can be reassigned another value:

      s = "Hello Again"

      Escape Sequences

      Within a double-quoted string literal, escape sequences that begin with a backslash (\) can be used to insert arbitrary byte values into the string. The most common are:

      • \a - “alert” or bell
      • \b - backspace
      • \f - form feed
      • \n - newline
      • \r - carriage return
      • \t - tab
      • \v - vertical tab
      • \' - single quote (only in the rune literal '\'')
      • \" - double quote (only within "..." literals)
      • \\ - backslash

      Runes, ASCII, Unicode and UTF

      And since we're talking Go Strings, Runes, ASCII  and Unicode, let's review a little about these topics.

      ASCII

      ASCII (American Standard Code for Information Interchange) is a character encoding standard created in the 60's and still widely used. ASCII's only supports 128 characters such as un-accented letters, numbers and a few other characters.

      Unicode

      Due to ASCII's limitations, Unicode was created as a superset of it. Today it defines over 140k characters (but capable of more than a million code points), more than sufficient to handle most of the characters and symbols present in the world. The Unicode standard defines Unicode Transformation Formats (UTF) UTF-8, UTF-16, and UTF-32, and several other encodings.

      UTF-8

      Today, UTF-8 is the most common encoding on the internet. UTF-8 was invented by Ken Thompson and Rob Pike, two of the creators of Go. It uses between 1 and 4 bytes to represent each rune but only one byte for ASCII characters, and 2 or 3 bytes for runes. The first 128 Unicode code points represent the ASCII characters, which means that any ASCII text is also a UTF-8 text.

      Unicode Standard Notation

      Unicode has the standard notation for codepoint, starting with U+, followed by its codepoint in hexadecimal. For example, U+1F600 represents the Unicode character 😀. To get the Unicode value in Go, use the %U verb.

      Printing Runes

      Runes are usually printed with the following verbs:

      • %c: to print the character
      • %q: to print the character within quotes
      • %U: to print the value of the character in Unicode notation (U+<value>) 

      For example:

      ascii := 'a'
      unicode := '😀'
      newline := '\n'
      fmt.Printf("%d %[1]c %[1]q\n", ascii)   // 97 a 'a'
      fmt.Printf("%d %[1]c %[1]q\n", unicode) // 22269 😀 '😀'
      fmt.Printf("%U\n", unicode)             // U+1F600
      fmt.Printf("%d %[1]q\n", newline)       // 10 '\n'

      Other formats can also be used, including:

      • %b: base 2
      • %o: base 8
      • %d: base 10
      • %x: base 16, with lower-case letters for a-f

      Raw String Literals

      A raw string literal is written using backticks (`). Within raw string literals, no escape sequences are processed; the contents are taken literally. For example:

      s := `{
      "name": "john"
      }`
      fmt.Println(s)

      Prints:

      {
      "name": "john"
      }

      Standard Library Support

      Strings are also widely supported by Go's standard library. The most important packages for manipulating strings are: bytes, strings, strconv, and unicode. We'll study them in future posts but feel free to explore and learn more about them at your own pace.

      Conclusion

      On this post we learned a little more about Strings in Go. Since manipulating Strings is an essential part of a programmer's life, understanding their particularities is important to master the Go programming language.

      To summarize, here are some important particularities that you should know:

      • strings in Go are immutable sequence of bytes
      • strings in Go can contain human-readable or any data including bytes
      • text strings in Go are conventionally interpreted as UTF-8-encoded sequences of Unicode code points (runes)
      • as Go files (which are always encoded in UTF-8) Go text strings are conventionally interpreted as UTF-8 and can include Unicode code points in string literals
      • strings in Go accept either ASCII characters as well as Unicode code points
      • a rune whose value is less than 256 can be written with a single hexadecimal escape (e.g., '\x41' for 'A') but \u or \U escape must be used for higher values

      See Also

      Tuesday, January 19, 2021

      Runes in Go

      Understand what's a rune in Go and when to use it

      If you are new to Go, you probably saw the word rune being used. But would you be able to precise what it is?

      Runes in Go

      A rune in Go is essentially a synonym to the type int32 which by convention is set to an Unicode code point. A code point is a numerical value that can represent single characters but can also have other meanings, such as formatting. With UTF-8 encoding, different code points are encoded as sequences from one to four bytes long.


      For example, the rune literal ‘a’ is the ASCII code 97 or Unicode U+0061. In summary, a rune in Go is:

      • a synonym to the type int32
      • A type, with keyword rune aliased to the type int32
      • A Unicode codepoint
      • A character

      Rune Literals

      Another important point to remember is that Go code is encoded as UTF-8, meaning that string literals will use encoding by default and can be written as a character within single quotes.

      And as we'll see later, Go also accepts any ASCII character as well as Unicode code points either directly or with numeric escapes. For example, a rune whose value is less than 256 can be written with a single hexadecimal escape (e.g., '\x41' for 'A') but \u or \U escape must be used for higher values.

      ASCII, Unicode and UTF

      And since we're talking ASCII  and Unicode, let's understand why we should understand how they differ.

      ASCII

      ASCII (abbreviated from American Standard Code for Information Interchange) is a character encoding standard for electronic communication. It's development started in the 60's and still widely used today. 

      But ASCII is limited to only128 characters (or 7 bits with code points ranging from 0 to 127), which means that it only contains enough to hold un-accented letters, numbers and a few other characters, leaving out accents and most of the characters used by Eastern languages.

      Unicode

      For that reason, a new standard called Unicode was created as a superset of ASCII and defines over 140k characters (but capable of more than a million code points), more than sufficient to handle most of the characters in all languages present in the world plus new if necessary.

      Unicode can be implemented by different character encodings. The Unicode standard defines Unicode Transformation Formats (UTF) UTF-8, UTF-16, and UTF-32, and several other encodings. The most commonly used encodings are UTF-8, UTF-16, UCS-2 and GB18030, which's standardized in China and implements Unicode fully, while not an official Unicode standard.

      UTF-8

      Today, UTF-8 is the most common encoding on the internet. UTF-8 was invented by Ken Thompson and Rob Pike, two of the creators of Go, and is now a Unicode standard. It uses between 1 and 4 bytes to represent each rune but only one byte for ASCII characters, and 2 or 3 bytes for runes. The first 128 Unicode code points represent the ASCII characters, which means that any ASCII text is also a UTF-8 text.

      Unicode Standard Notation

      Unicode has the standard notation for codepoint, starting with U+, followed by its codepoint in hexadecimal. For example, U+1F600 represents the Unicode character 😀. To get the Unicode value in Go, use the %U format.

      Printing Runes

      Runes are usually printed with the following formats:

      • %c: to print the character
      • %q: to print the character within quotes
      • %U: to print the value of the character in Unicode notation (U+<value>) 

      For example:

      ascii := 'a'
      unicode := '😀'
      newline := '\n'
      fmt.Printf("%d %[1]c %[1]q\n", ascii)   // 97 a 'a'
      fmt.Printf("%d %[1]c %[1]q\n", unicode) // 22269 😀 '😀'
      fmt.Printf("%U\n", unicode)             // U+1F600
      fmt.Printf("%d %[1]q\n", newline)       // 10 '\n'

      But other formats can also be used, including:

      • %b: base 2
      • %o: base 8
      • %d: base 10
      • %x: base 16, with lower-case letters for a-f

      Conclusion

      On this post we learned about runes in Go. Runes are essentially an alias for int32 and is equivalent to int32 in all ways. It is used, by convention, to distinguish character values from integer values.

      See Also

      Tuesday, January 12, 2021

      Declaring Types in Go

      Learn how to declare your own types in Go.

      We recently reviewed both the standard way to declare variables, and tuple assignments. Let's extend on those concepts and learn how to declare our own types in Go.

      Types in Go

      A type in Go is a declaration that defines a new named type that we can use in our programs and follows this pattern:

      type name underlying-type

      Declaring our types

      So let's see how we can use the type keyword to declare our own types based on base data types or from our own structs.

      Declaring types based on Structs

      A common way to declare our own types is by combining the type and struct keywords. A struct is a custom type that groups different subtypes, known as fields.

      For example, if we were developing an application that reads users from a database, we could create the following User type with:

      type User struct {
      Name  string
      Email string
      }

      Then, we could assign values to it using with:

      u1 := User{"John", "john@mail.com"}

      Declaring types based on basic data types

      Another way to declare custom types is by declaring them based on basic data types. The advantage is by aligning to the business rules, our code gets more readable. For example: 

      type Inch float64
      type Centimeter float64

      func main() {
      var in Inch
      var cm Centimeter
      in = 10
      cm = 25.4
      fmt.Println(in, cm)
      }

      Comparing Types

      However, it's worth noticing one downside of the above declaration. Since two values of different named types cannot be compared directly by the compiler (even if both types are based on the float64 type), we cannot compare them directly:

      cm == in
      invalid operation: cm == in (mismatched types int and float64)

      The solution would be converting both to the same type and comparing them:

      fmt.Println(in == Inch(cm))
      false

      Which is not much intuitive, is it?

      Conclusion

      On this article we learned about declaring named types in Go. Using named types is recommended if it makes the code more readable (for example, to avoid writing out complex types repeatedly). However, consider creating them carefully if your types are based on basic data types since it may decrease readability.

      It's also possible to define custom behaviors for our types which we'll see in a future post. Keep tuned!

      See Also

      Tuesday, January 5, 2021

      Tuple Assignments in Go

      Learn about tuple assignments in Go and how to use it.

      Apart from the standard way to declare variables, Go offers another way known as tuple assignment. Tuple assignments allow declaring (and assigning) several variables at the same time with the caveat that the expressions on the right are evaluated before any of the variables are updated.

      Since tuple assignments are very frequently used in Go, let's see some ways to use it effectively.

      Quicker initialization

      The first obvious use of tuple assignment is to declare and assign multiple variables at once. The benefits are more readability and less verbosiness. For example:

      i, j, k := 2, 3, 4

      Variable Swap

      Variable swaps are significantly clearer in Go due to this feature. For example, here's how one would swap the values of x an y in Go:

      x, y = y, x

      And you could also run operations as needed. For example:

      x, y = y, x*2

      Multiple returned values

      Another common use is to capture values returned from a function that returns multiple results. For example, a call to os.Open:

      f, err := os.Open("file.txt")

      Similarly, you may be familiar with a similar pattern when using channels:

      v, ok = <-ch

      Or doing type assertion:

      v, ok = x.(T)

      Conclusion

      On this article we learned about tuple assignments in Go, which apart from the standard way to declare variables, is a very common pattern used in the languageTuple assignments allow declaring (and assigning) several variables at the same time with the caveat that the expressions on the right are evaluated before any of the variables are updated.

      See Also

      Tuesday, December 29, 2020

      Go Operators

      Want to know more about operators in Go? Read to understand.

      If you come from JavaScript, Java, C, C# or Python you will feel at home with Go operators. On this article we will provide a summary of the operators in Go and provide some examples.

      What are operators?

      But what are operators? Operators are constructs which behave generally like functions, but which differ syntactically or semantically. Common simple examples include arithmetic, comparison, and logical.

      Which operators are supported in Go?

      The following are the operators (including assignment operators) and punctuation supported in Go:

      +    &     +=    &=     &&    ==    !=    (    )
      -    |     -=    |=     ||    <     <=    [    ]
      *    ^     *=    ^=     <-    >     >=    {    }
      /    <<    /=    <<=    ++    =     :=    ,    ;
      %    >>    %=    >>=    --    !     ...   .    :
           &^          &^=
      

      Types of operators

      Go operators are usually categorized based on functionality:

      • Arithmetic Operators
      • Comparison Operators
      • Relational Operators
      • Logical Operators
      • Bitwise Operators
      • Assignment Operators
      • Misc Operators

      Arithmetic operators

      Arithmetic operators apply to numeric values and yield a result of the same type as the first operand. The four standard arithmetic operators (+, -, *, /) apply to integer, floating-point, and complex types; + also applies to strings. The bitwise logical and shift operators apply to integers only.

      +    sum                    integers, floats, complex values, strings
      -    difference             integers, floats, complex values
      *    product                integers, floats, complex values
      /    quotient               integers, floats, complex values
      %    remainder              integers
      
      &    bitwise AND            integers
      |    bitwise OR             integers
      ^    bitwise XOR            integers
      &^   bit clear (AND NOT)    integers
      
      <<   left shift             integer << unsigned integer
      >>   right shift            integer >> unsigned integer 

      Comparison operators

      Comparison operators compare two operands and yield an untyped boolean value. They are:

      ==    equal
      !=    not equal
      <     less
      <=    less or equal
      >     greater
      >=    greater or equal
      

      Logical operators

      Logical operators apply to boolean values and yield a result of the same type as the operands. The right operand is evaluated conditionally.

      &&    conditional AND    p && q  is  "if p then q else false"
      ||    conditional OR     p || q  is  "if p then true else q"
      !     NOT                !p      is  "not p" 

      Address operators

      For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal. If the evaluation of x would cause a run-time panic, then the evaluation of &x does too.

      For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x. If x is nil, an attempt to evaluate *x will cause a run-time panic.

      &x
      &a[f(2)]
      &Point{2, 3}
      *p
      *pf(x)
      
      var x *int = nil
      *x   // causes a run-time panic
      &*x  // causes a run-time panic 
      

      Operator precedence

      Unary operators

      Unary operators have the highest precedence. As the ++ and -- operators form statements, not expressions, they fall outside the operator hierarchy. As a consequence, statement *p++ is the same as (*p)++.

      Binary operators

      There are five precedence levels for binary operators. Multiplication operators bind strongest, followed by addition operators, comparison operators, && (logical AND), and finally || (logical OR).

      Precedence    Operator
          5             *  /  %  <<  >>  &  &^
          4             +  -  |  ^
          3             ==  !=  <  <=  >  >=
          2             &&
          1             ||
      

      Binary operators of the same precedence associate from left to right. For instance, x / y * z is the same as (x / y) * z.

      +x
      23 + 3*x[i]
      x <= f()
      ^a >> b
      f() || g()
      x == y+1 && <-chanPtr > 0
      

      Conclusion

      On this article we discussed a little about Go operators. If you come from JavaScript, Java, C, C# or Python you will feel at home with Go operators. Knowing and understanding operators in any programming language is important for writing better and readable code, we recommend that you read the Go spec for more information.

      Source

      Tuesday, December 22, 2020

      The new function in Go

      Know everything about the new function in Go, especially when and how to use it.

      Apart from the standard way to declare variables, Go offers another way to declare variables via the built-in function new function. Its format is:

      myVar := new(myType)

      Can you guess what's the type for myVar on the example above? If you guessed *myType, you got it right: the new function returns a pointer to the specified type. So let's understand a little more about it.

      A deeper look

      Because new always returns a pointer to the specified type, it's fair to say that as with pointers, every call to the new  function will create an unnamed variable, initialize it its zero value and return its address, a pointer to the specified type. For example:

      package main

      import (
      "fmt"
      )

      func main() {
      p := new(int)
      fmt.Printf("p: %v, *p: %v, &p: %v", p, *p, &p)
      }


      p: 0xc000100010, *p: 0, &p: 0xc000102018

      When to use the new function?

      And when should we use new?

      The main reason to use new is that you don't need to declare a new variable just to assign values to your pointers, with the tradeoff that your code becomes less readable.

      Think of it as a convenience to abbreviate the three-step process of declaring and assigning values to pointers:

      // this block
      i := 22
      var p *int
      p = &i

      // could be replaced by this
      p := new(int)
      *p = 22

      Conclusion

      On this article we learned about the new function in Go. One of the advantages of using new is that you don't need to declare a dummy variable to assign your pointers to it. But since new returns a pointer to the specified type, it may be confusing for new users of the language. For that reason, the new function is not very used but definitely, it's worth knowing.

      See Also

      Tuesday, December 15, 2020

      Escape Sequences in Go

      Want to know more about escape sequences in Go? Read to understand.

      Go as other programming languages has the concept of escaping. A escaping sequence is a combination of characters that has a meaning other than the literal characters contained therein. An escaping sequence commonly uses a escape character which in Go is the \ character. Let's understand more about escaping in Go's context.

      Why escape?

      Escaping is a commonly used technique that developers use resort to escaping code to:

      • encode commands or special data which cannot be directly represented by the alphabet.
      • represent characters which cannot be typed in the current context, or would have an undesired interpretation

      Escaping in Go

      As other programming languages, Go utilizes the backslash (\) character to escape. What to use next? Depends on what you need. Here are some useful values to get you started:

      Escape Sequence Value
      \\ the \ character
      \' the ' character
      \" the " character
      \? the ? character
      \a an alert
      \b backspace
      \f form feed
      \n a new line
      \r carriage return
      \t an horizontal tab
      \xFF hexadecimal "FF"

      Examples

      So let's check some examples:

      package main

      import (
      "fmt"
      )

      func main() {
      dec := 22
      octal := 033
      hex := 0xFF
      fmt.Printf("Decimal %v, Hex: %v, Octal: %v\n", dec, hex, octal)
      fmt.Println("Some\ttab")
      fmt.Println("A quote: \"")
      fmt.Println("What\nabout\nline\nbreaks")
      }

      Decimal 22, Hex: 255, Octal: 27
      Some tab
      A quote: "
      What
      about
      line
      breaks

      Conclusion

      On this article we learned about escaping. Escaping in Go is very similar to other programming languages and is extensively used to encode commands or special data which cannot be directly represented by the alphabet or to represent characters which cannot be typed in the current context, or would have an undesired interpretation.

      Reference

      See Also

      Tuesday, December 8, 2020

      Go Reserved Keywords

      Go is not a big language but would you be able to list all of its reserved keywords?

      On a recent post we reviewed the main keywords on a Go program. On that article we discussed that some of the reasons to use Go are that it's easy to learn and scales so well is due to its simplicity. In fact, the language is so small that it may be very simple for a new user of the language to get accustomed to it very quickly.

      But that's not a coincidence. The language was built with simplicity as a core value meaning that every modification in the language (especially those increasing it) is extensively debated by the community.

      Go Keywords

      Go has 25 reserved keywords are:

      • break
      • case
      • chan
      • const
      • continue
      • default
      • defer
      • else
      • fallthrough
      • for
      • func
      • go
      • goto
      • if
      • import
      • interface
      • map
      • package
      • range
      • return
      • select
      • struct
      • switch
      • type
      • var

      Note that because the above keywords are reserved, you cannot name your variables using one of those words.

      Predeclared names

      In addition to the predeclared keywords, these are the predeclared names you'll see in Go:

      • Constants: true, false, iota, nil
      • Types: int, int8, int16, int32, int64 uint, uint8, uint16, uint32, uint64, uintptr float32, float64, complex128, complex64 bool, byte, rune, string, error
      • Functions:  make, len, cap, new, append, copy, close, delete, complex, real, imag panic, recover

      Predeclared names are nor reserved by the language, meaning you're free to use them (with moderation) in your code whenever it makes sense. For example, this code would work:

      func main() {
      len := 15
      fmt.Println("Len:", len)
      }

      While this wouldn't:

      func main() {
      goto := 15
      fmt.Println("Goto:", goto)
      }

      ./prog.go:8:7: syntax error: unexpected :=, expecting name
      ./prog.go:9:22:syntax error: unexpected goto, expecting expression

      Conclusion

      On this post we learned about Go's reserved keywords. If you're new to Go but not to programming, you definitely would be able identify most of them!

      When developing in Go it's important to understand its reserved keywords as you will be constantly interacting with them. While will discuss more each of the above keywords in future posts, we also recommend you to understand well how variables and zero values work in Go.

      Reference

      Tuesday, December 1, 2020

      Constants in Go

      Want to know more about constants in Go? Read to understand

      On a previous post we discussed variables in Go. We also learned what zero values are. Today we will focus on understanding what are constants in Go and how to use them.

      What is a constant?

      Almost every programming language has the concept of constants. Constants are variables that hold immutable values, values that you can't change when your program is running. In Go, they're declared by using the const keyword and can only hold values that the compiler knows at compile time.

      Let's see some examples:

      // declare one const named maxAge of type int
      const maxAge int = 100

      // declare bool const
      const active = false

      // declare multiple consts at the same time
      const (
            siteName   = "Golang4us"
            email = "mail@mail.com"
      )

      // declare a const maxRecords assigning a value to it
      const maxRecords = 200 * 10

      What cannot be a constant

      Knowing what can be a constant is only part of the equation. The other part is knowing what cannot. Since in order to be a constant, the compiler has to know its value at compile time, anything calculated or available at runtime cannot be. And that applies to common types like arrays, slices, maps or structs.

      Typed and Untyped Constants

      There are two ways to declare constants in Go:

      1. typed: defines the type and can only be assigned to a variable of the same type
      2. untyped: works as a literal. Has no type but can have its type inferred by the compiler
      You can see how they work in the examples below:
      // a typed constant
      const a name = "Adam"

      // an untyped constant
      const age = 42

      As you may expect, although no type was specified for the variable age, the compiler will infer via its assigned value (42) that its type is int.

      Checking a constant's type

      In case you want, you can verify the types of your constants by using the %T formatter. For example, the program below would print: Age 42 is of type int
      package main

      import (
      "fmt"
      )

      func main() {
      const age = 42
      fmt.Printf("Age %v is of type %T", age, age)
      }

      When to use constants?

      But when and why use constants? The rule of thumb is to use them whenever you need to reference a value that doesn't change. You could definitely hardcode constants in your code but setting them in constants in your code keeps the code DRY, making it more readable, refactorable and maintainable.

      Reference

      See Also

      Monday, November 23, 2020

      Zero Values in Go

      Would you be able to define what is a Zero Value in Go?

      On a previous article we discussed all about variables. However, declaring variables is just one piece of the equation. Since go does not have nulls, would you be able to tell what value  each primitive type is assigned?

      If you though zero values then you're right. But would you be able to tell how to declare and use them 

      On this article let's continue our discussion on variable initialization in Go discussing Zero Values.

      Zero Values

      One important difference between Go and other programming languages is that in Go, a variable cannot be null (or undefined). In Go, variables declared and not initialized will have a default value associated to them also known as Zero Value.

      Zero values are an important concept of Go and worth understanding well regardless of your programming skills. One of the big advantages they provide is that, by not having nulls, your code will not be subject to Null Pointer Exceptions, one of the biggest reason for bugs, crashes and security issues in other programming languages.

      How to set Zero Values?

      But how do we set variables to their zero values? If you read our previous tutorial you know that every variable non-initialized by default set its zero value.

      Confusing? Better learn from an example then.

      On the program below, none of variables was initialized thus, set to their respective zero value. Would you be able to tell what's this program outputs?

      package main

      import "fmt"

      func main() {
      var i int
      var f float64
      var b bool
      var s string
      var arr [3]string     // an array[3] of strings
      fmt.Printf("%v %v %v %v %v\n", i, f, b, s, arr)
      }

      If you guessed 0 0 false "" [ ] congratulations! So let's see which are the zero values for the most common types.

      Zero Values for Common Types

      The zero values for the most common types:

      • int, float64 (and other numeric types): 0
      • bool: false
      • string: "" (empty string)
      • arrays/slices: [ ] (empty, not null/nil)
      • custom types: {} (we'll learn about them later)

      When to use Zero Values?

      The last topic to cover about zero values is when to use them? Well, if you have experience in other programming languages you understand that you don't always have the value you need at hand. For all these use cases, you should declare your variables without initializing them. For example:

      var b bool

      Conclusion

      On this article we learned about Zero Values in Go. Zero Values are an important concept in Go that's worth understanding as they're widely used in Go programs and libraries. Learning and using Zero Values is important to make your code more robust and readable.

      See Also

      Monday, November 16, 2020

      Variables in Go

      Understand all about declaring and using variables in Go

      Once you understand the main reasons to use Go, installed Go on your Windows, Linux or Mac, and built your first program in Go, it's time to dive into the details of the language. While most developers are familiar to these concepts, Go approaches that in different ways that are worth exploring.

      Built-in types

      Variables are essential to any programming language. In Go, the built-in types are boolean, integer, float and string. The language also offers support for arrays, maps and declaring our custom types which we'll see in a future article.

      Another aspect that's worth mentioning is that Go is a statically typed programming language, meaning that the variable type is inferred before compilation.

      On this post we well study:

      1. the basics of variables in Go
      2. declaring variables with the "var" keyworkd
      3. declaring variables using the shorthand syntax
      4. zero values

      The basics of variables in Go

      So let's start with the basics of variables in Go. Essentially:

      • there are two ways to initialize variables
      • it's possible to declare and initialize multiple variables (and values) at the same time
      • there are no null variables in Go
      • Every value has a default value (also called Zero Value)
      • you can access/pass values via pointers
      • the compiler does not allow unused variables
      Let's discuss them.

      Declaring variables using the “var” keyword

      The first way to initialize variables in Go is by using the var keyword. For example:

      package main

      import "fmt"

      func main() {
           var name = "John Smith"                 // Snippet 1
           var email string = "john@smith.com"     // Snippet 2
           var address string                      // Snippet 3
           var age int                             // Snippet 4
           fmt.Println(name, email, address, age)  // Snippet 5                           
      }

      Where, on:

      1. Snippet 1: we declared a variable assigned a value to it. Go infers the type from the initialization automatically for us
      2. Snippet 2: similar to snippet 1 but specifying our type. Note: this use is not recommended as its unnecessarily verbose. In Go, we prefer simplicity
      3. Snippet 3: we declared a variable of type string but didn't assign any value to it. Go will set its zero value which is "" (empty).
      4. Snippet 4: we declared a variable of type int but didn't assign any value to it. Go will set its zero value which is 0.
      5. Snippet 5: we print our variables. This program will not build if we don't use the variables we declare.

      Declaring variables using the shorthand syntax

      While the above makes sense if you know the value of the variable you could initialize it more concisely with the following syntax:

      package main

      import "fmt"

      func main() {
         name := "John Smith"
         age := 32
         fmt.Println(name, age)
      }

      On both examples we declared a variable and assigned a value to it. Go infers the type from the initialization automatically for us (string and int on this case).

      However there are two things to notice about this syntax. First, the := operator cannot be used to reasign a value to an already declared variable. Think of its purpose as declare and set. So, if you tried to update the name var to something else, you'd get this error:

      no new variables on left side of :=

      Another thing to note is that the shorthand syntax for declaring a variable does not work outside of a function. For example, the example below:

      package main
      import "fmt"

      name := "John Smith"

      func main() {
          age := 32
          fmt.Println(name, age)
      }

      Would fail with:

      syntax error: non-declaration statement outside function body

      To properly initialize it, we should have used the var keyword as in:

      package main
      import "fmt"

      var name = "John Smith"

      func main() {
          age := 32
          fmt.Println(name, age)
      }

      Declaring multiple variables at the same time

      Go also allows you to declare (and set values for) multiple variables at the same time using the abbreviated syntax:

      package main
      import "fmt"

      func main() {
          name, id:= "John Smith", 123456           // Snippet 1
          fmt.Println(name, id)
      }

      Or, by wrapping them around the var keyword:

      package main
      import "fmt"

      func main() {
          var (
             a int
             b = 1
             c int = 2
             d, e = 3, "test"
             f, g string
           )
          fmt.Printf("%v %v %v %v %v %v %v\n", a, b, c, d, e, f, g)
      }

      Note that the above syntax only works if you if you provide values for all variables. 

      name, email := "John" // error: no value specified for email

      Unused Variables

      It's important to note that every variable declared in Go must be used. You will get a compile-time error if your code has an unused variable. And that's a good thing since it makes the code cleaner and less error-prone.

      The special identifier _

      Go also offers the special identifier _ which can be assigned values. It works as a black hole meaning that values assigned to it will be ignored and will save you from declaring (and reading) a variable you don't need too. We'll cover more about this special variable in future posts.

      Naming Variables

      Variables in Go are usually declared using the "camel case" syntax. Go also does not impose any restrictions on the size but usually smaller is preferred. And as in most languages, variables can be named using standard ascii characters with the difference that Go also accepts any Unicode character considered a letter or digit. For example, the below code would work:

      π := 3.14159
      fmt.Println("The value of pi is", π)

      The value of pi is 3.14159

      However, we recommend keeping it simple and only using ASCII chars for your variables:

      name := "John"
      age := 22
      fmt.Printf("%v is %v years old", name, age)

      Tuple Assignments

      Keep in mind the difference between := and =. The first is a declaration while the second is an assignment. In Go, we saw that we can do multiple assignments at the same time:

      i, j = j, i // swap values of i and j

      Zero Values

      Another important concept in Go is Zero Values. While we will study them later, for now, we want you to understand that in Go, no variable will ever be null. Variables declared and not initialized will have a default value associated to them (aka, zero value).

      Zero values are an important concept of Go and worth understanding well if you come from other programming languages. For more information, check this article.

      Conclusion

      On this post we studied different ways to declare and initialize our variables. We also discussed some errors that may occur and provided recommendations on how to use them. We hope it helps!

      See Also

      Monday, November 9, 2020

      The main keywords in a Go program

      Learning Go? Understand the main keywords you'll need to write Go programs

      Once you understand the main reasons to use Go, installed Go on your Windows, Linux or Mac, and built your first program in Go, it's time to dive into the details of the language. On this tutorial we will continue studying our first program in Go to understand some of the important concepts of the language.

      If you recall our previous post, in Go, a typical hello world written is as: 

      package main

      import "fmt"

      func main(){
          fmt.Println("Hello World")
      }

      Since we already learned how to build and run our first Go program today we'll review each line of our program to understand some of the keywords you'll use while developing in Go.

      package main

      Any Go program (or project) should one and only have one main function, but multiple files can be present on the same package, in our case, package main. We'll learn more about packages in the future but to keep it simple, what we want you to know for now is that, to create your own program in Go, you should have a function names main() in a packaged named main.

      import "fmt"

      The next line is import "fmt". There are two important keywords here:

      1. import: tells the compiler that we want to import an external dependency into our project
      2. fmt: the name of our dependency

      The import keyword

      It's common for our programs to depend on other functionality. In Go, external functionality is wrapped in packages and the import keyword is used to do so. In our example, we imported fmt to have access to the standard output as we'll see next.

      The fmt package

      Now stop for a second and think: how did our first program in Go printed a line to the console? The answer is that, that functionality was provided by the Println function of the fmt package which contains the code necessary to interact with the output of our console. We'll learn more about it next.

      fmt stands for formatting and is the default package for input and output and it's documentation is available here. In our example, it was used to grant access to the Println function required to print contents in our terminal. We'll learn more about it later.

      func main() {

      Next we enter our main function. In Go, you declare a function as func <functionName>.

      Another important point to note is that, as previously explained, in order to be executed, every Go program has to have one - and only one - main function. It's also common (and recommended but not mandatory) to name the file that contains the main function as main.go.

      The { is the operator Go utilizes to create blocks. You'll see it being closed in the last two lines

      fmt.Println("Hello World")

      Once our program initializes this is the first thing that gets executed is the line fmt.Println("Hello World"). There are 3 important things in this line:

      1. fmt.Println: we're calling the function Println from the fmt package
      2. We're passing the string "Hello World" to it.

      Since Go is not an object-oriented language, everything is a function. And accessing the functions of our packages is nothing more than: pkg_name.Function_Name.

      If you want to learn more about the package fmt, check this page.  

      The { and } operators

      The { and } operators wrap functions, conditional statements and in our example were used to wrap the main function logic.

      Conclusion

      On this post we continued our introduction to Go basics and provided a line-by-line explanation of the our first program in Go. But wait! There's a lot more to learn about those keywords that we'll explain in future articles. 

      References

      See Also

      Monday, November 2, 2020

      Your first program in Go

      Beginning in Go? Learn how write your first program in this fantastic programming language

      Once you installed Go on your Windows, Linux or Mac and understand why you should use Go, let's build our first Go program, shall we?

      What's a Hello World program

      Writing a simple Hello World program is the traditional way to learn a new programming language. It consists essentially in writing as little code as possible to print the "Hello World" sentence on the screen. In its simplicity lies its beauty: teaching a new programmer how to get the minimum in place to start interacting with the computer.

      In Go, a typical hello world written is as: 

      package main

      import "fmt"

      func main(){
          fmt.Println("Hello World")
      }

      But writing the program is just the first step. In order to make it print the expression Hello World on the screen we'll need to run our program.

      Creating our first Go Project

      So let us help you organize your first Go project. Create a folder called hello-world in a directory on your machine (for example ~/src). Inside it, create a file called main.go, paste the above contents (highlighted in gray) using your favorite editor and save it. This is the structure we expect you to have:

      ~/src$ tree hello-world/
      hello-world/
      └── main.go

      0 directories, 1 file

      Running our Program

      Now let's run our program. Since Go provides go run, a command that both compiles and runs our programs, let's use it this time. In the same folder where your main.go is, run in a terminal:

      ~/src/hello-world$ go run main.go
      Hello World
      Congratulations, you just ran your first Go program!

      Compiling your Program

      It's important to reiterate what the go run command did previously: it compiled and ran our program. Since Go is a statically-typed programming language, the compilation step is required in order to run our code. Compiling is the process to transform source code into machine code. So let's now see how to do it in two steps.

      Inside the hello-world folder, type:

      go build

      You should see this (where hello-world is our executable):

      ~/src/hello-world$ go build
      ~/src/hello-world$ ls
      hello-world  main.go

      Run it with:

      ./hello-world

      Yay! You should see "Hello World" being outputted on your console:

      ~/src/hello-world$ ./hello-world
      Hello World

      Conclusion

      On this post we learned how to create our first Go program. There's a lot more to understand about that program but we'll keep those details for the future. Since Go is a statically-typed programming language, you as a developer will have to compile it and run it first. Go provides these tools called go run and go build.

      See Also

      Any comment about this page? Please contact us on Twitter

      Featured Article

      Pointers in Go

      Understand all about declaring and using pointers in Go If you're coming from Python, Java, JavaScript, C# and others, tal...

      Popular Posts