Golang Pointers | Find Output Programs | Set 2

This section contains the Golang pointers find output programs (set 2) with their output and explanations.
Submitted by Nidhi, on October 21, 2021

Program 1:

package main

import "fmt"

func main() {
	var val string = "hello"
	var ptr *string

	ptr = &val
	fmt.Printf("%s\n", *ptr)
	fmt.Printf("%c\n", ptr[1])
}

Output:

./prog.go:11:24: invalid operation: ptr[1] (type *string does not support indexing)

Explanation:

The above program will generate a syntax error because we cannot indexing with string pointer.


Program 2:

package main

import "fmt"

func main() {
	var s *int
	fmt.Println("s = ", s)
}

Output:

s =  <nil>

Explanation:

The variable s is uninitialized, and the uninitialized pointer variable's value is nil.


Program 3:

package main

import "fmt"

func main() {
	x := 10
	var s *int

	s = &x

	if s == &x {
		fmt.Println("True...")
	} else {
		fmt.Println("False...")
	}
}

Output:

True...

Explanation:

Here, the variable s is an integer pointer and x is an integer variable, s is initialized with the address of x, s contains the address of x. Thus, the condition is true.

Golang Find Output Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.