Monday, April 17, 2023

How Convert Pointer *bool to bool or *string to string in go lang functions

Most of the use cases in any technology the functions will be returning the some response either in string ,bool,float,int or some custom struct format. This is the basis use case in our regular programming.

Similarly in Go language if your writing any simple functions will return the same data types mentioned above or sometimes as pointer reference also will be returned.

In case if function returning the pointer reference how to converted the same pointer reference to it's underlying data type will be discussed in this post. If we are not converting we will be receiving the error as  "cannot use yourvariableName (variable of type *bool/string/int) as bool/string/int value in assignment compilerIncompatibleAssign "

Example : Pointer bool to bool or pointer string to string

package main

import "fmt"

func main() {
	var resp *bool
	resp = isNewToGoLang("8888888888")
	var isNewVar bool
	if resp != nil {
		isNewVar = *resp
		fmt.Println("Is New Var ", isNewVar)
	}
}

func isNewToGoLang(mobile any) *bool {

	varFalse := false
	varTrue := true
	if mobile == nil {
		return nil
	}
	if mobile != nil {
		return &varTrue
	}
	return &varFalse
}

Please comment or write us if you have any queries/requirements.

Please like,follow,bookmark,subscribe this site to receive daily updates.


FaceBook Page - I Love Coding. You?


Hope this helps you..Enjoy..!

No comments:

Post a Comment