[go: up one dir, main page]

0% found this document useful (0 votes)
88 views34 pages

CodeCademy Go

The document provides an introduction to the Go programming language. It discusses how Go aims to improve productivity and scalability compared to other languages. It also covers Go's built-in support for concurrency and garbage collection. The document then demonstrates how to compile and run Go programs, and shows the basic structure of Go programs including packages, imports, functions, variables, types, and comments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views34 pages

CodeCademy Go

The document provides an introduction to the Go programming language. It discusses how Go aims to improve productivity and scalability compared to other languages. It also covers Go's built-in support for concurrency and garbage collection. The document then demonstrates how to compile and run Go programs, and shows the basic structure of Go programs including packages, imports, functions, variables, types, and comments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

CodeCademy Go

Introduction
Go, or golang is an open sourced programming language. The designers of Go aimed to
“eliminate the slowness and clumsiness of software development at Google, and thereby to make
the process more productive and scalable”. It has modern features like garbage collection and it
also takes advantage of multi-core computer capabilities with built-in concurrency support.
Go uses a compiler. To compile a program written in Go, we write:
go build program.go // replace “program.go” with your written program
./program // to execute the file
The go run command combines both the compilation and the execution of the code for us. It will
not create an executable file in our current folder.
go run program.go // will compile and execute program
Every go program starts with a package declaration, which informs the compiler whether to create
an executable or library. With a library being a collection of code that can be used in other
programs. Programs with the package declaration package main will create an executable file.
Go ignores whitespace, but it makes code easier to read. The import keyword allows us to bring in
and use code from other packages. Package names are enclosed in double quotes. Packages
group related code together, allow code to be reusable and make it easier to maintain. We only
import packages that are used.
Code 4/9:
package main

import "fmt" // finish next lesson

Functions exist in go, start with func and have curly braces.
A file that has a package main declaration will automatically run the main function.
Code 5/9:
package main

import "fmt"

func main() { // main function is like main method in java


fmt.Println("Hello world")
}

We can use a single import with a pair of parentheses that contain our packages. We separate
each package on a different line. We can also provide an alias to a package by including the alias
name before the file, making it easier to refer to the package.
Code 6/9:
package main

import "fmt"
import t "time"

func main() {
fmt.Println("Hello World")
fmt.Println(t.Now())
}
Comment using // and /* */
Code 7/9:
package main

import "fmt"

func main() {
//Are we racing or coding?
/*
fmt.Println("Ready")
fmt.Println("Set")
*/
fmt.Println("Gooooo!")
}

Use go doc to use Go’s own built-in documentation system.


Code 8/9:
package main

import "fmt"

func main() {
fmt.Println("Using the 'go doc' command is helpful")
fmt.Println("You can find out more about a package")
fmt.Println("Or about a function inside the package")
fmt.Println("Try it out in the terminal!")
}

Gopher It
Code:
package main

import (f "fmt" t "time")

func main() {
f.Println(" `.-::::::-.` ")
f.Println(".:-::::::::::::::-:.")
f.Println("`_::: :: :::_`")
f.Println(" .:( ^ :: ^ ):. ")
f.Println(" `::: (..) :::. ")
f.Println(" `:::::::UU:::::::` ")
f.Println(" .::::::::::::::::. ")
f.Println(" O::::::::::::::::O ")
f.Println(" -::::::::::::::::- ")
f.Println(" `::::::::::::::::` ")
f.Println(" .::::::::::::::. ")
f.Println(" oO:::::::Oo ")
f.Println(t.Now())
}
Variables and Types
Go has literals, an unnamed fixed value in source code. These can be written into code as it and
can have arithmetic operation performed on them.
Code 2/15:
package main

import "fmt"

func main() {
// Add a fmt.Println() statement
// that prints 2235 * 1231
fmt.Println(2235 * 1231)
}

There are also named values like constants and variables. Constants cannot be updated when the
program is running. Use the const keyword to create a Constant.
Code 3/15:
package main

import "fmt"

func main() {
// Create the constant earthsGravity
// here and set it to 9.80665
const earthsGravity = 9.80665
// Here's where we print out the gravity:
fmt.Println(earthsGravity)
}

Complex numbers are pairs of floating-point numbers where the second part of the pair is marked
with the “imaginary” unit i. They are useful when reasoning in 2-dimensional space and have other
utilizations that make them relevant for involved calculations. Examples include: 3i, 7+2i, -14 -.05i
Go has 15 different numeric types that fall into three categories: int, float and complex. This
includes 11 different integer types, 2 different floating-point types and 2 different complex number
types. Types also indicate how many bits will be used to represent the data. Integers can be
broken down into two categories: signed and unsigned. Unsigned integers can only be positive.
Booleans are either true or false. It only needs one bit to store a Boolean value.
A variable must be named and can change during the running of the program unlike a constant.
In go variables or constants that are exported at the package level (that is, identifiers that can be
used form a package other than the one where they are defined) must begin with a capital letter.
https://stackoverflow.com/questions/38616687/which-way-to-name-a-function-in-go-camelcase-or-
semi-camelcase
Code 6/15:
package main

func main() {
// Create the variable jellybeanCounter
// here and make its type int8
var jellybeanCounter int8 // shows error as not used
}

Go code will not compile if a imported library or a variable/constant is not used.


Code 7/15:
package main

import "fmt"

func main() {
var jellybeanCounter int8

// Go will raise errors both for


// jellybeanCounter being unused
// and for "fmt" being imported
// and unused.

// Uncomment the following line


// and watch the program run
// successfully!

fmt.Println(jellybeanCounter)
}
Code 8/15:
package main

import "fmt"

func main() {
var numOfFlavors int
// Assign a value for numOfFlavors below:
numOfFlavors = 57

fmt.Println(numOfFlavors)

// Declare flavorScale below:


var flavorScale float32 = 5.8

fmt.Println(flavorScale)

A string is a sequence of data, or text of any length.


Code 9/15:
package main

import "fmt"

func main() {
// Define a string variable
// called favoriteSnack
var favoriteSnack string

// Assign a value to
// favoriteSnack
favoriteSnack = "kladfjs"

// Print out the message


// "My favorite snack is "
// followed by the value in
// favoriteSnack
fmt.Println("My favorite snack is " + favoriteSnack)
}
All numeric variables have a default value of 0 before assignment, Strings have “” and Booleans
are false.
Code 10/15:
package main

import "fmt"

func main() {
// Create three variables
// emptyInt an int8
var emptyInt int8
// emptyFloat a float32
var emptyFloat float32
// and emptyString a string
var emptyString string
// Finally, print them all out
fmt.Println(emptyInt, emptyFloat, emptyString)
}

We can use the := operator to declare a variable without explicitly stating its type. We might use it
if we know what value we want our variable to store when creating it. Floats created in this way
are of type float64. Integers are either int32 or int64 depending on the size of the architecture.
We can use a separate syntax instead to declare a variable and infer its type:
var variableName = true
Code 11/15:
package main

import "fmt"

func main() {
// Define daysOnVacation using := below:
daysOnVacation := 5

// Define hoursInDay using var and = below:


var hoursInDay = 24

fmt.Println("You have spent", daysOnVacation * hoursInDay, "hours on


vacation.")
}
Computers have a default length for the data in their ROM. If the computer is using 32-bit
architecture then int’s will be defaulted to int32 otherwise if 64-bit architecture then int’s will be
defaulted to int64. It is recommended to use int unless there’s a reason to specify the size of the
int. To make an int unsinged (only positive) use uint, you can still specify size. := operator will
default to int not uint.
Code 12/15:
package main

import "fmt"

func main() {
// Define cupsOfCoffeeConsumed here
var cupsOfCoffeeConsumed int
// Give a value to cupsOfCoffeeConsumed
cupsOfCoffeeConsumed = 5123
// Print out cupsOfCoffeeConsumed
fmt.Println(cupsOfCoffeeConsumed)
}

Code 13/15:
package main

import "fmt"

func main() {
coolSneakers := 65.99
niceNecklace := 45.50

// Define taxCalculation here


var taxCalculation float64
// Add coolSneakers to taxCalculation
taxCalculation += coolSneakers
// Add niceNecklace to taxCalculation
taxCalculation += niceNecklace
// Compute the NYC sales tax
// 8.875% of the purchase here:
taxCalculation *= 0.08875
// Uncomment this line for a receipt!
fmt.Println("Purchase of", coolSneakers + niceNecklace, "with 8.875%
sales tax", taxCalculation, "equal to", coolSneakers + niceNecklace +
taxCalculation)
}
we can declare multiple variables on a single line.
Code 14/15:
package main

import "fmt"

func main () {
// Define magicNum and powerLevel below:
var magicNum, powerLevel int32
magicNum = 2048
powerLevel = 9001
fmt.Println("magicNum is:", magicNum, "powerLevel is:", powerLevel)
// Define amount and unit below:
amount, unit := 10, "doll hairs"
fmt.Println(amount, unit, ", that's expensive...")
}

Comic Mischief
Code:
package main

import "fmt"

func main(){
var publisher, writer, artist, title string
var year, pageNumber uint // unsigned as positive vars
var grade float32
title = "Mr. GoToSleep"
writer = "Tracey Hatchet"
artist = "Jewel Tampson"
publisher = "DizzyBooks Publishing Inc."
year = 1997
pageNumber = 14
grade = 6.5
fmt.Println(title, "written by", writer, "drawn by", artist,
"published by", publisher, "made in", year, "total pages", pageNumber,
"grade", grade)
title = "Epic Vol. 1"
writer = "Ryan N. Shawn"
artist = "Phoebe Paperclips"
year = 2013
pageNumber = 160
grade = 9.0
fmt.Println(title, "written by", writer, "drawn by", artist,
"published by", publisher, "made in", year, "total pages", pageNumber,
"grade", grade)
}
fmt Package
fmt is one of Go’s core packages. It has a broader purpose of helping us format data.
Print() prints data but with no newline at the end. Printf() can print formatted data.
Sprint(), Sprintln() and Sprintf() is used to format data but not print it.
Scan() can scan for input.
More: https://golang.org/pkg/fmt/
Println() prints it arguments with an included space between each argument.
Print() does not and also does not provide a line break after.
Code 2/8:
package main

import "fmt"

func main() {
fmt.Println("Let's first see how", "the Println() method works.")
fmt.Println("Notice that each statement adds a newline for us.")
fmt.Println("There's also a default space", "between the string
arguments.")

// Add your code below:


fmt.Print("Print","is","different")
fmt.Print("See?")
}

Using fmt.Printf() we can interpolate strings, leave placeholders in a string and use values to fill in
the placeholders. The %v is our place holder and is known as a verb in Go.
Code 3/8:
package main

import "fmt"

func main() {
animal1 := "cat"
animal2 := "dog"

// Add your code below:


fmt.Printf("Are you a %v or a %v person?", animal1, animal2)
}
Go has a variety of useful verbs. %T will get the type of an argument. %d is used for numbers
%f is used for floats and we can limit how precise we are by including a value between the % and
the f like: %.2f.
Code 4/8:
package main

import "fmt"

func main() {
floatExample := 1.75
// Edit the following Printf for the FIRST step
fmt.Printf("Working with a %T", floatExample)

fmt.Println("\n***") // Added for spacing

yearsOfExp := 3
reqYearsExp := 15
// Edit the following Printf for the SECOND step
fmt.Printf("I have %d years of Go experience and this job is asking
for %d years.", yearsOfExp, reqYearsExp)

fmt.Println("\n***") // Added for spacing

stockPrice := 3.50
// Edit the following Printf for the THIRD step
fmt.Printf("Each share of Gopher feed is $%.2f!", stockPrice)
}

Sprint() and Sprintln() format strings but don’t print them. They return a string instead.
Code 5/8:
package main

import "fmt"

func main() {
step1 := "Breathe in..."
step2 := "Breathe out..."

// Add your code below:


meditation := fmt.Sprintln(step1, step2)
fmt.Print(meditation)
}
Code 6/8:
package main

import "fmt"

func main() {
template := "I wish I had a %v."
pet := "puppy"

var wish string

// Add your code below:


wish = fmt.Sprintf(template, pet)

fmt.Println(wish)
}

fmt.Scan() allows us to get user input. fmt.Scan(&response) takes the first value before a space
and stores it in the var response. If we were expecting two values we would need to declare two
variables ahead of time. fmt.Scan() expects addresses for arguments, hence the & before.
Code 7/8:
package main

import "fmt"

func main() {
fmt.Println("What would you like for lunch?")

// Add your code below:


var food string
fmt.Scan(&food)
fmt.Printf("Sure, we can have %v for lunch.", food)
}

More methods: https://golang.org/pkg/fmt/


Conditionals
if (true/false) {} // parentheses are optional
Code 2/13:
package main

import "fmt"

func main() {
heistReady := false
if heistReady {
fmt.Println("Let's Go!")
}
}

if (true/false) {} else {}
Code 3/13:
package main

import "fmt"

func main() {
heistReady := false

if heistReady {
fmt.Println("Let's go!")
} else {
fmt.Println("Act normal.")
}
}

== equal to != not equal to


Code 4/13:
package main

import "fmt"

func main() {
lockCombo := "2-35-19"
robAttempt := "1-1-1"

// Add your code below:


if (lockCombo == robAttempt) {
fmt.Println("The vault is now opened.")
}
}
< less than > greater than <= less or equal to >= greater or equal to
Code 5/13:
package main

import "fmt"

func main() {
vaultAmt := 2356468

// Add your code below:


if (vaultAmt >= 200000) {
fmt.Println("We're going to need more bags.")
}
}

&& And || Or ! not


Code 6/13:
package main

import "fmt"

func main() {
rightTime := true
rightPlace := true

// Edit this condition for the FIRST checkpoint


if rightTime && rightPlace {
fmt.Println("We're outta here!")
} else {
fmt.Println("Be patient...")
}

enoughRobbers := false
enoughBags := true

// Edit this condition for the SECOND checkpoint


if enoughRobbers || enoughBags {
fmt.Println("Grab everything!")
} else {
fmt.Println("Grab whatever you can!")
}
}
! not
Code 7/13:
package main

import "fmt"

func main() {
readyToGo := true

if !readyToGo {
fmt.Println("Start the car!")
} else {
fmt.Println("What are we waiting for??")
}
}

if () {} else if () {} else {}
Code 8/13:
package main

import "fmt"

func main() {
amountStolen := 64650

if amountStolen > 1000000 {


fmt.Println("We've hit the jackpot!")
} else if (amountStolen >= 5000) {
fmt.Println("Think of all the candy we can buy!")
} else {
fmt.Println("Why did we even do this?")
}
}
A switch statement allows us to test the value of a variable and compare it with multiple cases.
Code 9/13:
package main

import "fmt"

func main() {
name := "H. J. Simp"

// Add your switch statement below:


switch (name) {
case "Butch":
fmt.Println("Head to Robbers Roost.")
case "bonnie":
fmt.Println("Stay put in Joplin.")
default:
fmt.Println("Just hide!")
}
}
We can also include a short variable declaration before we provide a condition in either if or switch
statements, declaring a variable to be used in the comparison. The declared variable is scoped to
the statement blocks, so that it can only be accessed within the blocks of those statements.
Code 10/13:
package main

import "fmt"

func main() {
if success := true; success {
fmt.Println("We're rich!")
} else {
fmt.Println("Where did we go wrong?")
}

amountStolen := 50000

switch numOfThieves := 5; numOfThieves {


case 1:
fmt.Println("I'll take all $", amountStolen)
case 2:
fmt.Println("Everyone gets $", amountStolen/2)
case 3:
fmt.Println("Everyone gets $", amountStolen/3)
case 4:
fmt.Println("Everyone gets $", amountStolen/4)
case 5:
fmt.Println("Everyone gets $", amountStolen/5)
default:
fmt.Println("There's not enough to go around...")
}
}
Use the math/rand library to help us generate a random integer
Code 11/13:
package main

import (
"fmt"
"math/rand"
)

func main() {
// Edit amountLeft below:
amountLeft := rand.Intn(10000)

fmt.Println("amountLeft is: ", amountLeft)

if amountLeft > 5000 {


fmt.Println("What should I spend this on?")
} else {
fmt.Println("Where did all my money go?")
}
}

Go seeds or chooses a number as a starting point for generating random numbers.


use rand.Seed() to provide a new seed value by passing in an integer. Each time we run our
program, we also need a unique number as a seed. We can use time to be our unique number as
its always a different time when our program is run. Use the time library, and
time.Now().UnixNano(). This results in the difference in nanoseconds since January 1 st, 1970
UTC.
Code 12/13:
package main

import (
"fmt"
"math/rand"
"time"
)

func main() {
// Add your code below:
rand.Seed(time.Now().UnixNano())

amountLeft := rand.Intn(10000)

fmt.Println("amountLeft is: ", amountLeft)

if amountLeft > 5000 {


fmt.Println("What should I spend this on?")
} else {
fmt.Println("Where did all my money go?")
}
}

Bank Heist
Code:
package main

import (
"fmt"
"math/rand"
"time"
)

func main() {
rand.Seed(time.Now().UnixNano())
isHeistOn := true
eludedGuards := rand.Intn(100) // 0-99
if (eludedGuards >= 50) {
fmt.Println("Looks like you've managed to make it past the guards.
Good job, but remember, this is the first step.")
} else {
isHeistOn = false
fmt.Println("Plan a better disguise next time?")
}
openedVault := rand.Intn(100)
if (isHeistOn && openedVault >= 70) {
fmt.Println("Grab and GO!")
} else if (isHeistOn) {
isHeistOn = false
fmt.Println("Vault cannot be opened")
}
leftSafely := rand.Intn(5) // 0-4
if (isHeistOn) {
switch (leftSafely){
case 0:
isHeistOn = false
fmt.Println("Failed heist")
case 1:
isHeistOn = false
fmt.Println("Failed heist")
case 2:
isHeistOn = false
fmt.Println("Failed heist")
case 3:
isHeistOn = false
fmt.Println("Failed heist")
default:
fmt.Println("Start the getaway car!")
}
if isHeistOn {
amtStolen := 10000 + rand.Intn(1000000)
fmt.Printf("Amount taken: %d \n", amtStolen)
}
}

fmt.Printf("Heist is on: %t",isHeistOn) // %t is bool


}

Functions
A function is a block of code designed to be reused
Code 2/9:
package main

import "fmt"

// Define eatTacos() here:


func eatTacos() {
fmt.Println("Yum!")
}

func main() {
// Call your function here:
eatTacos()
}

Scope is a concept that refers to where the values and functions are defined and where they can
be accessed. You can only refer to variables or functions defined within a specific namespace.
Code 3/9:
package main

import "fmt"

func startGame() {
instructions := "Press enter to start..."

fmt.Println(instructions)
}

func main() {
startGame()
}

A function can be given a return type. It needs a return statement to pass back a value and stop
the function from executing any more code.
Code 4/9:
package main
import (
"fmt"
"time"
)

// Add "string" as the return type of this function


func isItLateInNewYork() string{
var lateMessage string
t := time.Now()
tz, _ := time.LoadLocation("America/New_York")
nyHour := t.In(tz).Hour()
if nyHour < 5 {
lateMessage = "Goodness it is late"
} else if nyHour < 16 {
lateMessage = "It's not late at all!"
} else if nyHour < 19 {
lateMessage = "I guess it's getting kind of late"
} else {
lateMessage = "It's late"
}

// Return the string lateMessage


return lateMessage
}

func main() {
var nyLate string
nyLate = isItLateInNewYork()
fmt.Println(nyLate)
}

Use parameters to provide functions with information. If all parameters have the same type we can
only write the type once at the end.
Code 5/9:
package main
import "fmt"

// Update marsYear so that it takes earthYears


// As a parameter
func computeMarsYears(earthYears int) int {
// Remove earthYears definition within marsYear
earthDays := earthYears * 365
marsYears := earthDays / 687
return marsYears
}

func main() {
myAge := 25

// Call `marsYear` with `myAge`


myMartianAge := computeMarsYears(myAge)
fmt.Println(myMartianAge)
}

Code 6/9:
package main
import (
"math"
"fmt"
)

// Define specialComputation() here


func specialComputation(x float64) float64{
return math.Log2(math.Sqrt(math.Tan(x)))
}

func main() {
var a, b, c, d float64
a = .0214
b = 1.02
c = 0.312
d = 4.001

// Replace the following four lines with specialComputation()


a = specialComputation(a)
b = specialComputation(b)
c = specialComputation(c)
d = specialComputation(d)

fmt.Println(a, b, c, d)
}

Functions can return multiple values


Code 7/9:
package main
import "fmt"
// Update getLikesAndShares to return two ints
func getLikesAndShares(postId int) (int, int) {
var likesForPost, sharesForPost int
switch postId {
case 1:
likesForPost = 5
sharesForPost = 7
case 2:
likesForPost = 3
sharesForPost = 11
case 3:
likesForPost = 22
sharesForPost = 1
case 4:
likesForPost = 7
sharesForPost = 9
}
fmt.Println("Likes: ", likesForPost, "Shares: ", sharesForPost)
// Add in a return for likesForPost and sharesForPost
return likesForPost, sharesForPost
}

func main() {
var likes, shares int

// Update this line so the results of the function


// get stored in "likes" and "shares"
likes, shares = getLikesAndShares(4)

if likes > 5 {
fmt.Println("Woohoo! We got some likes.")
}
if shares > 10 {
fmt.Println("We went viral!")
}
}

defer tells go to run a function but at the end of the current function, this is useful for logging, file
writing and other utilities.
Code 8/9:
package main
import "fmt"
func queryDatabase(query string) string {
defer disconnectDatabase()
var result string
connectDatabase()
// Add deferred call to disconnectDatabase() here

if query == "SELECT * FROM coolTable;" {


result = "NAME|DOB\nVincent Van Gogh|March 30, 1853"
}
fmt.Println(result)
return result
}

func connectDatabase() {
fmt.Println("Connecting to the database.")
}

func disconnectDatabase() {
fmt.Println("Disconnecting from the database.")
}

func main() {
queryDatabase("SELECT * FROM coolTable;")
}

Interstellar Travel
Code:
package main
import "fmt"

// Create the function fuelGauge() here


func fuelGauge(fuel int) {
fmt.Println(fuel)
}

// Create the function calculateFuel() here


func calculateFuel(planet string) int {
var fuel int
switch planet {
case "Venus":
fuel = 300000
case "Mercury":
fuel = 500000
case "Mars":
fuel = 700000
default:
}
return fuel
}

// Create the function greetPlanet() here


func greetPlanet(planet string) {
fmt.Printf("Ariving at %s \n", planet)
}

// Create the function cantFly() here


func cantFly() {
fmt.Println("We do not have the available fuel to fly there.")
}

// Create the function flyToPlanet() here


func flyToPlanet(planet string, fuel int) int {
fuelRemaining := fuel
fuelCost := calculateFuel(planet)
if (fuelRemaining >= fuelCost) {
greetPlanet(planet)
fuelRemaining -= fuelCost
} else {
cantFly()
}
return fuelRemaining
}

func main() {
// Test your functions!

// Create `planetChoice` and `fuel`


fuel := 1000000
planetChoice := "Venus"
// And then liftoff!
fuel = flyToPlanet(planetChoice, fuel)
fuelGauge(fuel)
}

Addresses and Pointers


Go is a pass-by-value language. When we are calling a function with an argument, the Go
compiler is strictly using the value of the argument rather than the argument itself. We need to
make use of addresses, pointers and dereferencing to change values from different scopes.
The space that the computer allocates for values is called an address, and each one is marked as
a unique numerical value. To find the variables address use the & operator, like in C. The address
is returned in hexadecimal format.
Code 2/6:
package main

import "fmt"

func main() {
treasure := "The friends we make along the way."

// Add your code below:


fmt.Println(&treasure)
}

Pointers are variables that specifically store addresses. The * operator signifies that a variable will
store an address. We can also declare a pointer implicitly like other variables using :=.
Code 3/6:
package main

import "fmt"

func main() {
star := "Polaris"

// Add your code below:


starAddress := &star // or var starAddress *string
fmt.Println("The address of star is", starAddress)

Dereferencing (or indirecting) is using a pointer to access the address and change its value.
We need to use the * operator on a pointer and then assign a new value.
Code 4/6:
package main
import "fmt"

func main() {
star := "Polaris"

starAddress := &star

// Add your code below:


*starAddress = "Sirius"

fmt.Println("The actual value of star is", star)


}

We can make functions using pointers and dereferencing to change variables in another scope
Code 5/6:
package main

import "fmt"

// Change brainwash to have a pointer parameter


func brainwash(saying *string) {
// Dereference saying below:
*saying = "Beep Boop."
}

func main() {
greeting := "Hello there!"

// Call your brainwash() below:


brainwash(&greeting)

fmt.Println("greeting is now:", greeting)


}

Code 1/10:

You might also like