Go has confusing pointers

113 views
Skip to first unread message

chris...@gmail.com

unread,
Jun 19, 2020, 1:23:53 PM6/19/20
to golang-nuts
Hi,
Please help me understand the below:
I got this from "The Zoo of Go Functions"

type Count int

func (c *Count) Incr() int {
 *c = *c + 1 //why use *c and not just c, based on (c *Count) c is already a pointer?
 return int(*c) //why cast to int, c is already of type int? 
}

Christof

Michael Jones

unread,
Jun 19, 2020, 1:39:30 PM6/19/20
to chris...@gmail.com, golang-nuts
this says "increment the data c points at" not "increment the pointer"

the function is returning an int instead of a Count 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/47bb77be-9634-47cb-9899-3bb07328ee50o%40googlegroups.com.


--
Michael T. Jones
michae...@gmail.com

Tyler Compton

unread,
Jun 19, 2020, 1:44:26 PM6/19/20
to chris...@gmail.com, golang-nuts
 *c = *c + 1 //why use *c and not just c, based on (c *Count) c is already a pointer?

In Go (as well as other languages like C) '*' plays two roles. When used with a type like in "c *Count", it tells you that c is a pointer to a Count object. When used on a variable, like "*c + 1", it dereferences the pointer. In other words, "*c + 1" gets the value that "c" is pointing to and adds one to that value.
 
why cast to int, c is already of type int? 

In this case, c is of type Count, not int. When you define a type in Go, you're defining a new distinct type, not an alias to the underlying type. The Count type is distinct from int, even though it's based on int.

howar...@gmail.com

unread,
Jun 19, 2020, 1:49:33 PM6/19/20
to golang-nuts
c is of type *Count (pointer to Count), surely? It is (*c) that is of type Count, which has to be cast to int to be returned as such because Go requires explicit casts. Agree with the rest.

Tyler Compton

unread,
Jun 19, 2020, 1:55:50 PM6/19/20
to howar...@gmail.com, golang-nuts
c is of type *Count (pointer to Count), surely?

Yes, my mistake! Thank you for the correction.
Reply all
Reply to author
Forward
0 new messages