strings, arrays


package main
import "fmt"

func main() {
    var numbers =[4]int{1, 2, 3, 4}
    var name = []string{"j", "i", "m"}

    fmt.Println(numbers[0], numbers[1], numbers[2], numbers[3])
    fmt.Println(name[0], name[1], name[2])
    fmt.Printf("name: %s\n", name[0] + name[1] + name[2])
}

/*
1 2 3 4
j i m
name: jim
*/

arrays


package main
import "fmt"

func main() {
    var ages = []int{1, 2, 3, 4, 5}
    fmt.Println(ages)
}

// [1 2 3 4 5]

but doing this...

package main
import "fmt"

func main() {
    var ages = [15]int{1, 2, 3, 4, 5}
    fmt.Println(ages)
}

...you will get a different result:

// [1 2 3 4 5 0 0 0 0 0 0 0 0 0 0]

To access an element from the array...
package main
import "fmt"

func main() {
    var ages = []int{1, 2, 3, 4, 5}
    fmt.Println(ages)
    fmt.Println(len(ages))
    fmt.Println(ages[2])
}

/*
[1 2 3 4 5]
5
3
*/

loops - 3 kinds



package main
import "fmt"

func main() {
    target := 1
    //while loop
    for target > 0 {
        fmt.Printf("\nNumber of loops?\n")
        fmt.Scanf("%d", &target)
        //for loop
        for i := 0; i < target; i++ {
            fmt.Printf("%d", i)
        }
    }
    //infinite loop
    for {
        //explicitly terminated
        break
    }
}

// 0123456789
*source: The Go Programming Language, David Chisnall

error constant overflows int



Running this script...
package main
import "fmt"

func main() {
    universe := 1024 * 1024 * 1024 * 1024
    fmt.Printf("the universe is %v\n", universe)
}

...gives me the error:
# command-line-arguments
./a.go:9: constant 1099511627776 overflows int

To fix this, I had to define what type var universe is going to be, uint64
package main
import "fmt"

func main() {
    var universe uint64 //or float64
    universe = 1024 * 1024 * 1024 * 1024
    fmt.Printf("the universe is %v\n", universe)
}

switch example



Write a program that allows the user to enter the grade scored in a class (0 - 100). If the user scored a 100, then notify that they got a perfect score.

Modify the prorgam so that if the user scored a 90 - 100, it informs the user that they scored an A.

Modify the program so that it will notify the user of their letter grade... 0 - 59: F, 60 - 69: D, 70 - 79: C, 80 - 89: B, 90 - 100: A

package main
import "fmt"

func main() {
    var score float64
    fmt.Println("Enter score for your last exam: ")
    fmt.Scanf("%v", &score)
    switch {
    case score <= 59:
        fmt.Println("Your grade is F")
    case score <= 69:
        fmt.Println("Your grade is C")
    case score <= 79:
        fmt.Println("Your grade is D")
    case score <= 89:
        fmt.Println("Your grade is B")
    case score <= 100:
        fmt.Println("Your grade is A")
    default:
        fmt.Println("Please enter a score <= 100")
    }
}

* The issue with this script is that if user enters a string, they still get a grade (F). What I want to happen is that the script will tell the user to input a number.

I will update this later...

guess the number game v2



In C++...
#include 
#include 
#include 
using namespace std;

int main() {
    srand(static_cast(time(0))); //seed random number generator
    int secretNumber = rand() % 10 + 1; //random num bet 1 and 100
    int tries = 0;
    int guess;

    cout << "\tWelcome to Guess My Number\n\n";
    do {
        cout << "Enter a guess: ";
        cin >> guess;
        ++tries;

        if (guess > secretNumber) {
            cout << "Too high!\n\n";
        }
        else if (guess < secretNumber) {
            cout << "Too low!\n\n";
        }
        else {
            cout << "\nThat's it! You got it in " << tries << " guesses\n";
        }
    } while (guess != secretNumber);

    return 0;
}
In golang...
package main
import (
    "fmt"
    "math/rand"
    "time"
)

func xrand(min, max int) int {
    rand.Seed(time.Now().Unix())
    return rand.Intn(max - min) + min
}

func main() {
    myrand := xrand(1, 10)
    tries := 0
    var guess int

    fmt.Println("Welcome to Guess My Number Game!")
    for guess != myrand {
        fmt.Println("Take a guess...")
        fmt.Scanf("%v", &guess)
        tries++
        if guess > myrand {
            fmt.Println("Too high")
        } else if guess < myrand {
            fmt.Println("Too low")
        } else {
            fmt.Printf("Good job! You guessed it in %v tries", tries)
            break
        }
    }
}

loops: break continue


Expected result...
/*
1
2
3
4
6
7
8
9
10
*/

In C++
#include 
using namespace std;

int main() {
    int count = 0;
    while (true) {
        count += 1;
        //end loop if count is greater than 10
        if (count > 10) {
            break;
        }
        //skip 5
        if (count == 5) {
            continue;
        }
        cout << count << endl;
    }
}
In golang...
package main
import (
    "fmt"
    "time"
)

func main() {
    test := 0
    for {
        test += 1
        if test > 10 {
            break
        }
        if test == 5 {
            continue
        }

        fmt.Println(test)
        time.Sleep(300 * time.Millisecond)
    }
}

while true loop infinity



In C++...
#include 
using namespace std;

int main() {
    int test = 10;
    while(test == 10) {
        cout << test;
    }
}
In golang...
package main
import "fmt"

func main() {
    test := 10
    for test == 10 {
        fmt.Println(test)
    }
}

maps



package main
import "fmt"

func main() {
    m := make(map[string]string)
    m["answer"] = "first"
    fmt.Println("the value:", m["answer"])
    m["answer"] = "second"
    fmt.Println("The value:", m["answer"])
}
/*
the value: first
The value: second
*/

true or false



I was going through some python code and wondered how I can convert the snippet below into golang...
print 2 + 3 < 4 + 5
Here's what I think...
package main
import "fmt"
func main() {
    fmt.Println(2 + 3 > 4 + 5)
}

cpp to go: convert degreesC to degreesF



From C++
#include 
using namespace std;

int main()
{
    //enter the temp in C
    int celsius;
    cout << "Enter the temperature in Celsius: ";
    cin >> celsius;

    //convert C into F values
    int fahrenheit;
    fahrenheit = celsius * 9/5 + 32;

    //output the results(followed by a new line)
    cout << "Fahrenheit value is: ";
    cout << fahrenheit << endl;

    return 0;
}
...to golang:
package main
import "fmt"

func main() {
    var celsius float64
    fmt.Printf("Enter the temperature in Celsius: ")
    fmt.Scanf("%g", &celsius)

    var fahrenheit float64
    fahrenheit = celsius * 9/5 + 32
    fmt.Printf("Fahrenheit value is: %g\n", fahrenheit)
}

multi line strings



Use back ticks, instead of the usual double quotes

package main
import "fmt"

func main() {
    longString :=
    `this is
    a very, very
    very long string
    notice the back ticks`
    fmt.Println(longString)
}

calculate present value OR future value


package main
import (
    "fmt"
    "math"
)
var (
    interest,
    futureValue,
    period,
    presentValue,
    rate, //converts interest into decimal... interest / 100
    pvFactor,
    ratex float64 //used to compute pvfactor
)
func main() {
    fmt.Println("Enter 1 to calculate present value")
    fmt.Println("Enter 2 to calculate future value")
    var whichCalc int
    fmt.Scanf("%d", &whichCalc)
    if whichCalc == 1 {
        pvCalc()
    } else if whichCalc == 2 {
        fvCalc()
    } else {
        fmt.Println("You did not make a choice. Now closing.\n")
    }
}
func fvCalc() {
    //fv = pv * (1 + i)**t
    // http://www.accountingcoach.com/online-accounting-course/84Xpg02.html
    fmt.Println("Enter interest amount: ")
    fmt.Scanf("%g", &interest)
    rate = interest / 100
    fmt.Println("Enter present value: ")
    fmt.Scanf("%g", &presentValue)
    fmt.Println("Enter time period: ")
    fmt.Scanf("%g", &period)
    ratex = (1 + rate)
    pvFactor = math.Pow(ratex, period)
    futureValue = presentValue * pvFactor
    fmt.Println("Future value is = %g\n", futureValue)
}
func pvCalc() {
    //pv = fv * (1 /(1 +i)**n) 
    // http://www.accountingcoach.com/online-accounting-course/80Xpg03.html
    fmt.Println("Enter interest amount: ")
    fmt.Scanf("%g", &interest)
    rate = interest / 100
    fmt.Println("Enter future value: ")
    fmt.Scanf("%g", &futureValue)
    fmt.Println("Enter time period: ")
    fmt.Scanf("%g", &period)
    fmt.Printf("period is %g\n", period)
    ratex = (1 + rate)
    pvFactor = math.Pow(ratex, period)
    presentValue = futureValue * (1 / pvFactor)
    fmt.Printf("Present value is = %g\n", presentValue)
}

calculate present value


package main
import (
    "fmt"
    "math"
)

func main() {
    pvCalc()
}

func pvCalc() {
    var (
        interest,
        futureValue,
        period,
        presentValue,
        rate,
        pvFactor,
        ratex float64
    )
    fmt.Println("Enter interest amount: ")
    fmt.Scanf("%g", &interest)
    rate = interest / 100
    fmt.Println("Enter future value: ")
    fmt.Scanf("%g", &futureValue)
    fmt.Println("Enter time period: ")
    fmt.Scanf("%g", &period)
    fmt.Printf("period is %g\n", period)
    ratex = (1 + rate)
    pvFactor = math.Pow(ratex, period)
    presentValue = futureValue * (1 / pvFactor)
    fmt.Printf("Present value is = %g\n", presentValue)
}

math.Pow


package main
import (
    "fmt"
    "math"
)
func main() {
    var xpow, ypow, mynum float64
    xpow = 10
    ypow = 2
    mynum = math.Pow(xpow, ypow)
    fmt.Printf("you get %g\n", mynum)
}
// you get 100

write unicode character


To write a Unicode-character in code preface the hexadecimal value with \u or \U.
Because they need at least 2 bytes we have to use the int16 or int type. If 4 bytes are needed for the character \U is used; \u is always followed by exactly 4 hexadecimal digits and \U by 8 .

package main
import "fmt"
func main() {
    ch := '\u0041'
    ch2 := '\u03B2'
    ch3 := '\U00101234'
    fmt.Printf("%d = %d - %d\n", ch, ch2, ch3)
}
//65 = 946 - 1053236

source--The Way To Go

string.count in go



package main
import (
    "fmt"
    "strings"
)
func main() {
    words := "hello world"
    fmt.Printf("Number of l's in %s is: ", words)
    fmt.Printf("%d\n", strings.Count(words, "l"))
}

string.length in go


package main
import "fmt"
func main() {
    words := "hello world"
    fmt.Println(len(words))
}