New Function
Lesson 3 of 19 in Coddy's Functions and Pointers in Golang course.
In the last lessons, we learned that variables are objects or spaces in memory with a name that points to that space.
In Go, we have a function that creates unnamed space in memory, and we do that with the help of the new() function. The syntax is as follows:
coddy := new(string)Here, we created an object with the name coddy and type string, and the new() function returns a pointer to that object (space).
If we print the name, we will get the memory address of this space:
fmt.Println("Value:", coddy)The result will be:
Value: 0xc000014070We can reassign a value to this pointer like this:
coddy := new(string)
*coddy = "Learn To Code with coddy"
fmt.Println("Value:", *coddy)The result will be:
Value: Learn To Code with coddyNote that when we create pointers with the new() function, the default value is not nil. It depends on the type, just like variables. If the type is int, the default value is 0; for string, it's an empty string; and for boolean, it's false.
Challenge
EasyWrite a program that takes an input from the user and does the following:
- Creates a pointer with type int using the new() function.
- Prints the default value of the pointer.
- Assigns the value entered by the user to that pointer.
- Prints the value of the pointer after assignment.
Try it yourself
package main
import (
"fmt"
)
func main() {
// Take input from the user Don't change this!
var num int
fmt.Scanln(&num)
// Create a pointer with type int using the new() function.
// Prints the default value of the pointer.
fmt.Println("Default value of the pointer:", ?)
// Assigns the value entered by the user to that pointer
// Prints the value of the pointer after assignment.
fmt.Println("Value of the pointer after assignment:", ?)
}
All lessons in Functions and Pointers in Golang
1Introduction
Introduction4Rebuild Go Strings Functions
Strings in GolangJoin FunctionContains FunctionIndex FunctionRecap Challenge #1