Skip to content

Instantly share code, notes, and snippets.

@deoren
Last active February 27, 2018 19:48
Show Gist options
  • Save deoren/3c4d3ca613b66c72ee27dae4b946c832 to your computer and use it in GitHub Desktop.
Save deoren/3c4d3ca613b66c72ee27dae4b946c832 to your computer and use it in GitHub Desktop.
Go scratch notes

Golang Scratch Notes

Assignment + Declaration vs assignment

:=

TODO: Confirm this statement

Using this operator results in a declaration (automatically I believe) and initial assignment. You can't go back later and use the operator again to assign a different value to the variable.

=

TODO: Confirm this statement

This is an assignment operator. This is used to assign a value to a variable that has been previously declared.

Specify source file as the startup file for the application

  • package main (declaration that it is the main package)
  • main() function without arguments

Single quotes vs Double quotes

Single quotes designate a byte, rather than a string

Example from "Getting input from the console" (from Learning Go @ Lynda.com)

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
str, _ := reader.ReadString('\n')

Parse functions do not automatically trim spaces

They also tend to fail if you do not trim them first.

Example code:

package main

import (
    "fmt"
    "bufio"
    "os"
    "strconv"
)

func main() {
    
    // var s string
    // fmt.Scanln(&s)
    // fmt.Println(s)

    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    str, _ := reader.ReadString('\n')
    fmt.Println(str)
    
    fmt.Print("Enter a number: ")
    str, _ = reader.ReadString('\n')
    f, err := strconv.ParseFloat(str, 64)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Value of number:", f)
    }
}

This results in this error: strconv.ParseFloat: parsing "45\r\n": invalid syntax

Fix:

  1. Import strings package
  2. Call strings.TrimSpace() on str variable

Example snippet:

    fmt.Print("Enter a number: ")
    str, _ = reader.ReadString('\n')
    f, err := strconv.ParseFloat(strings.TrimSpace(str), 64)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Value of number:", f)
    }

By trimming the spaces, the strconv.ParseFloat() function succeeds.

@deoren
Copy link
Author

deoren commented Feb 27, 2018

As of the time this Gist entry was created, GitHub does not support notifications for comments for mentions to Gist entries (see isaacs/github#21 for details). Please contact me via Twitter or file an issue in the deoren/leave-feedback repo (created for that very purpose) if you wish to receive a response for your feedback. Thank you in advance!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment