Redefining built in functions?

534 views
Skip to first unread message

JM Ibanez

unread,
Jul 30, 2011, 11:11:05 AM7/30/11
to golang-nuts
Hi folks,

I'm new to the group, and while playing around I coded something like
the code below. I'm wondering if the following makes any sense:

package main

import "fmt"

func main() {
slice := make([]int, 8)

len := len(slice)

fmt.Println(len)

// The next line won't compile, since len is now redefined as
// an int
// len2 := len(slice)

// fmt.Printf("%t", len)
// fmt.Println(len2)
}


I don't know if it's supposed to be flagged by the compiler, or if it
really is allowed to redefine a built-in's name. All things
considered, I tried adding a:

_len := len

but the compiler flagged it as invalid.

Thoughts?

JM Ibanez

Jesse McNelis

unread,
Jul 30, 2011, 11:25:27 AM7/30/11
to JM Ibanez, golang-nuts
On 31/07/11 01:11, JM Ibanez wrote:
> I don't know if it's supposed to be flagged by the compiler, or if it
> really is allowed to redefine a built-in's name. All things
> considered, I tried adding a:
>
> _len := len
>
> but the compiler flagged it as invalid.
>

The built-ins are just pre-declared identifiers.
But since they aren't really describable in Go you can't take a pointer
to the built-in functions. I mean, what type would "_len" have in this case?

You can declare functions, types, and variables in inner scopes that
will override those declared in outer scopes.

You can also do things like

type int float64
or
int := "somestring"
or
func somefunc(int,float string){
//int and float are variables of type string
}

Generally it's best to avoid these kinds of things. But means that Go
devs can add new types or built-in functions to the language in future
without breaking existing code that uses those names.

- jessta


Reply all
Reply to author
Forward
0 new messages