On Thu, 29 Sep 2016 09:38:24 -0700 (PDT)
T L <tapir....@gmail.com> wrote:

> > > I just expect type asserting on a non-nil interface value
> > > shouldn't 
> > panic. 
> >
> > of course it should panic if the interface holds an unexpected
> > value and you're not checking for correctness with the comma-ok
> > pattern. 
> >
> > Go is a statically typed language and by asserting the wrong type
> > on a variable you have an created an obviously incorrectly typed
> > program. If the compiler was able to deduce that the interface was
> > holding an incorrect value at compile time it would never have
> > allowed such a program to be compiled. 
> >
> > the following two examples both look ridiculous to a Go programmer: 
> >
> >     var i int = 42 
> >     var b = bool(i) 
> >     // b is now false 
> >
> > vs 
> >
> >    var i = interface{}(42) 
> >     var b = i.(bool) 
> >     // b is now false 
> >
> > One shouldn't be able to turn 42 into a "false" in Go. maybe in
> > other languages, but not Go. 
> 
> ok, maybe type assertion is really different from map element access,
> range over slice/map and read from channel.
> The later three can be viewed as special form of function callings,
> but type assertion can't.

I think you still can't "get" the chief distinction: it lies in typing
not in similarities of syntax.

For

  m := make(map[string]interface{})

there's a well-defined zero value for the type of values this map holds.

While somewhat dubious, this is useful for maps which merely record the
fact the particular set of keys is "known"; consider:

  m := make(map[string]bool)
  m["three"] = true

And now:

* m["one"] evaluates to false
* m["two"] evaluates to false
* m["three"] evaluates to true
* m["four"] evaluates to false
...and so on.

With type assertions, I really fail to see how returning the zero value
for the target type in case the type assertion failed can be useful.

That's because type assertions are really used for two cases:

* Conditional switching of the program flow -- such as in "when the
  actual type is T do this, otherwise do that".

* Actually _asserting_ the value is of particular type.
  To assert something means to verify a particular invariant about how
  the world behaves.

  To illustrate, you might assert that 4 / 2 == 2, and if this invariant
  fails, your runtime (or hardware or whatever) is broken and the only
  thing you can sensibly do is to crash your process.

-- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to