[go-nuts] Re: Build Issues on Ubuntu

2020-06-16 Thread Chris Hopkins
We have a winner!
Lots of attempts to read /usr/local/go/src/syscall, which is very read only
And not any go install it should be using, looks like GOTOOL was pointing 
at the wrong place(the default install, not any of the ones I did). No idea 
who is setting that up, but I can soon fix that.

Thanks!



On Tuesday, 16 June 2020 10:33:16 UTC+1, Brian Candler wrote:
>
> On Monday, 15 June 2020 21:59:21 UTC+1, Chris Hopkins wrote:
>>
>> The ubuntu default 1.14.4
>> https://dl.google.com/go/go1.14.4.src.tar.gz
>>
>
> What about the 1.14.4 precompiled binary?
> https://dl.google.com/go/go1.14.4.linux-amd64.tar.gz
>
> <https://dl.google.com/go/go1.14.4.linux-amd64.tar.gz>
> I <https://dl.google.com/go/go1.14.4.linux-amd64.tar.gz>t might be worth 
> looking at the last few pages of strace output just before it crashes:
> strace -f go build blah
> to see if it gives any clues.
>
>

-- 
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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/c1691022-6139-4481-b9cf-e9cdeda26910o%40googlegroups.com.


Re: [go-nuts] Build Issues on Ubuntu

2020-06-16 Thread Chris Hopkins
Yep, the asyncpreempt has definitly made it work.(But for how long Dun Dun 
Dun!!!)

Humm, interesting. Thanks I can do some more investigation now.


Kind Regards

Chris

On Monday, 15 June 2020 22:27:00 UTC+1, Ian Lance Taylor wrote:
>
> On Mon, Jun 15, 2020 at 1:59 PM Chris Hopkins  > wrote: 
> > 
> > Hi, 
> > (Sorry I've not been active in the group for a long time - job change 
> caused other changes!) 
> > I'm seeing a very strange error on building on one of my machines, in 
> fact I'm seeing it on any attempt to build any go project on that machine 
> e.g. 
> > 
> > ~/home/git/src/github.com/cbehopkins/medorg$ go build 
> check_calc/main.go 
> > check_calc/main.go:8:2: read /home/xxx/home/git/src/
> github.com/cbehopkins/medorg/checksum_test.go: read 
> /home/xxx/home/git/src/github.com/cbehopkins/medorg/checksum_test.go: 
> interrupted system call 
> > 
> > Builds on other machines work fine, so it's something specific to this 
> one. 
> > Literally a hello world does this. I suspected at first it being linked 
> to how that directory is mounted (it's a samba share), but the same happens 
> on the native file system. 
> > Go versions I've used: 
> > The ubuntu default 1.14.4 
> > https://dl.google.com/go/go1.14.4.src.tar.gz 
> > 14.4 built on a different machine and then copied locally (tricky to do 
> as it requires cross compliation). 
> > 
> > The only unique thing aboout this machine, is it is the only one on my 
> network that is both x86 & Linux, other combinations of x86 and OS work 
> fine. Any hints/ideas on how to debug this would be greatly appriciated. 
> (The OS is 
> > Ubuntu 20.04 LTS) 
>
> I don't know why this is happening, but you can probably make progress 
> by setting 
>
> GODEBUG=asyncpreemptoff=1 
>
> That won't fix the general problem, but it will make it happen less 
> frequently. 
>
> Ian 
>

-- 
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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/7ce84640-1dd8-4440-974c-945f1929ab43o%40googlegroups.com.


[go-nuts] Build Issues on Ubuntu

2020-06-15 Thread Chris Hopkins
Hi,
(Sorry I've not been active in the group for a long time - job change 
caused other changes!)
I'm seeing a very strange error on building on one of my machines, in fact 
I'm seeing it on any attempt to build any go project on that machine e.g.

~/home/git/src/github.com/cbehopkins/medorg$ go build check_calc/main.go 
check_calc/main.go:8:2: read 
/home/xxx/home/git/src/github.com/cbehopkins/medorg/checksum_test.go: read 
/home/xxx/home/git/src/github.com/cbehopkins/medorg/checksum_test.go: 
interrupted system call

Builds on other machines work fine, so it's something specific to this one.
Literally a hello world does this. I suspected at first it being linked to 
how that directory is mounted (it's a samba share), but the same happens on 
the native file system.
Go versions I've used:
The ubuntu default 1.14.4
https://dl.google.com/go/go1.14.4.src.tar.gz
14.4 built on a different machine and then copied locally (tricky to do as 
it requires cross compliation).

The only unique thing aboout this machine, is it is the only one on my 
network that is both x86 & Linux, other combinations of x86 and OS work 
fine. Any hints/ideas on how to debug this would be greatly appriciated. 
(The OS is 
Ubuntu 20.04 LTS) 

Kind Regards

Chris

-- 
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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/c481e6bc-eb38-43f2-9339-18e56db60bc9o%40googlegroups.com.


Re: [go-nuts] why is this not ascending?

2019-04-08 Thread Chris Hopkins
To a first order approximation, there is no guarantee of events between any 
two go processes. The scheduler is free to chose any unblocked process. 
Here's what I think is happening.

go sync () // creates the sync routine
fmt.Println("0") // prints
time.Sleep(time.Second) // sends this routine to sleep
// scheduler looks for work
fmt.Println("1")
time.Sleep(time.Second) // sends the other routine to sleep
// scheduler now has 2 routines waiting for a second to elapse
// sufficient timer ticks elapse for a second to be counted as passing
// both routines "unsleep" and are marked as being able to be scheduled
// scheduler looks for something to do
// may pick either routine, probably sensible though to go back to the last 
routine that did work
// (cache locality and all that)
fmt.Println("3")
time.Sleep(time.Second)
// scheduler looks for work
fmt.Println("2")

Again once you have work in the queue, the scheduler is free to schedule 
work from that queue in any order. The timer tick will probably (but not 
certainly) mean that both these routines unblock concurrently and so are on 
the work queue at the same moment.
Unless I am much mistaken the scheduler is architecturally free to swap 
between active routines at any time. I believe the current design will 
normally only evaluate the swap (cooperatively multi-task) on function 
calls (I could be mis-remembering this though).

HTH

Chris


On Monday, 8 April 2019 14:38:40 UTC+1, go je wrote:
>
> ascending only work if i cut the first sleep half second to print them 
> alternately but isn't they sequentially running?
>
> On Mon, Apr 8, 2019 at 9:30 PM go je > 
> wrote:
>
>> https://play.golang.org/p/0TIxVFuqGoB
>>
>> -- 
>> 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 golan...@googlegroups.com .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>
> -- 
>
>
>
>
>
> lol
>

-- 
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.


[go-nuts] Re: Why Go? What is the most important feature that led to you becoming a Go programmer?

2019-02-27 Thread Chris Hopkins
What brought me to it was the concurrency. I spent my entire career 
frustrated by not only how concurrency wasn't more of a thing in popular 
languages, but also how so many people didn't seem to think it was a 
problem. I pounced on Go when I heard about it. (Although I am currently 
fluttering my eyelashes at Halide...)

What made me stay is the clarity and simplicity. So many languages seem to 
be an exercise in showing off how clever you are, by using x clever 
pattern. Go doesn't seem to suffer this.

If I could just use it for the embedded stuff i do...

Chris

On Tuesday, 26 February 2019 12:07:58 UTC, Louki Sumirniy wrote:
>
> I just wanted to jot down and share my personal most important reason, and 
> make this thread a short sample of the most important aspect of Go that 
> drove you to learn and use it.
>
> For me, it was this: I have been tinkering with programming on and off 
> over the years since I was 8 years old, when a TRS-80 CoCo arrived in my 
> house, and in all the time, and with many languages, from BASIC, Assembler, 
> Amiga E (this was the first that really came close to this reason for me to 
> learn go), C, Python and Vala, but in all of these instances, until Go, I 
> was unable to do the most important thing, as I have very good visual 
> thinking skills, but poor attention - to be able to complete even a 
> relatively simple application. 
>
> My usual problem always was that I would get bogged down in some detail, 
> forget the bigger picture, and hit some big blocker in this detail and then 
> basically turn off the computer and go ride my skateboard. I have now 
> written several useful libraries, and massively extended and rewritten (now 
> around 80% done) a bitcoin-based cryptocurrency wallet/node server suite.
>
> Without Go's immediacy and simple, logical syntax and build system, I am 
> lost. Go may be unforgiving in its syntax and semantics, but this is good 
> because it's less decisions to make, and its really very possible with Go 
> to start writing code immediately, and figuring out how to slice up the 
> pieces and add new parts is far easier than in many other languages, start 
> from a very simple, vague base and sketch out the details bit by bit. No 
> other language has had this property that I have encountered before. I 
> often remark that the language's name and the short-attention-span and high 
> intelligence of many of its adopters have in common to some degree.
>
> I think part of it has to do with how one must be explicit with many 
> things, but at the same time, other places you can skip explications 
> because of the implicit, also lets you focus on what's important and not so 
> much distract you with superficial details.
>
> Many other languages force you to really separate coding and architecting, 
> Go lets you do it all on-the-fly.
>

-- 
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.


[go-nuts] Re: Understanding the doc (why can't I?)

2018-10-15 Thread Chris Hopkins
I've edited the example very slightly at:
https://play.golang.org/p/s7CUSbS8P3I

Let's break this down.
Think about how you might shuffle a pack of cards, a simple way is to swap 
2 cards around at a time. As long as you exchange enough cards enough times 
and both cards you chose are randomly picked, eventually you'll have 
shuffled the pack. Please be happy with that as a concept before going 
further.

The rand.Shuffle therefore doesn't care about what it has to shuffle. All 
it "thinks" about is: swap element 2 and 7, swap element 24 and 9 etc. (the 
numbers aren't important here, just that anything in an array can be 
shuffled by giving these sorts of instructions). All it needs to know is 
how long the array it has to shuffle is, and "who" can swap things around. 
I'll repeat that as it might not be obvious. It doesn't have to know how to 
swap things, it doesn;t have to know anything about the things. If I told 
you to shuffle 52 cards by shouting out numbers, the exact same instruction 
if you were instead shuffling 52 cars, or airplanes, or dogs; it's the 
number of things in the list and the numbers given as instructions that 
matter. It therefore only has to know of a function that can do this swap 
around. So we also pass it what I have called swapper. Who is an agent who 
you say, swap 2 and 7, 24 and 9, etc and it will do that.
So it can call swapper with i and j set to two values and swapper does the 
swap.

So how does this play into go:
Well we've declared the initial array as an array of words.
We've now declared swapper as someone who can carry out the function of 
swapping any 2 items in that array, that is the item at location i gets put 
at the position j was and the item at location j gets put where i was. I 
explicitly declared swapper as a func that takes two integers as that's the 
only thing rand.Shuffle knows or cars about the function. It just calls it 
a whole bunch of times, doesn't pay attention to anything it does, it just 
trusts it to do what needs to be done.
So as far as rand.Shuffle goes, it needs how many items are in the array, 
and a function that it can call with two integer parameters. so we sat to 
rand.shuffle what the length of the array is, and to use swapper.

And that's it. Don't worry about how rand.Shuffle works (until you want 
to). Yes it's a good bit of computer science to understand how it works, 
but it's also good computer science to accept that you don't need to know 
how things work under the hood either.

If that overly wordy version helps?

Chris
On Monday, 15 October 2018 15:06:58 UTC+1, Neil Higgins wrote:
>
> *Here's the doc for shuffle in math/random*:
>
> func Shuffle(n int , swap func(i, j int 
> ))
>
> Shuffle pseudo-randomizes the order of elements using the default Source. 
> n is the number of elements. Shuffle panics if n < 0. swap swaps the 
> elements with indexes i and j. 
>
> *And here's the example*:
>
> package main
>
> import (
> "fmt"
> "math/rand"
> "strings"
> )
>
> func main() {
> words := strings.Fields("ink runs from the corners of my mouth")
> rand.Shuffle(len(words), func(i, j int) {
> words[i], words[j] = words[j], words[i]
> })
> fmt.Println(words)
>
> }
>
> *Why can't I understand a word of it?*
> (This is not atypical, by the way - and not just for go - so if someone 
> can educate me, I might suddenly start prospering in the software game)
>
> Issues (for me):
>
>- Shuffle doesn't seem to swap anything (the thing you want shuffled 
>isn't even an argument)
>- As I read it the example, it should only swap two words (index i and 
>j) but it seems to shuffle the everything
>- What's this bloody "func" thing???
>- Why doesn't "swap" appear in the example?
>
> Yours sincerely,
> *Confused*
>

-- 
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.


[go-nuts] Casting Back from nested Struct

2018-10-10 Thread Chris Hopkins
Hi,
I appreciate this is not possible, but realised I never understood why (so 
have just been working around it).
Example code at:
https://play.golang.org/p/BgFL9T0KiC7

I can create a struct with other structs as a member. I then get all the 
fields and methods associated with that member.
But you can't cast from that master struct back to the member struct. 
i.e. I can create a type T with subtype S and operate on the members and 
data within S, but can't cast T to S.
I guessed that when you define type S, it exists as effectively a pointer 
to a struct, and then members within that struct are an indexed offset from 
that pointer. The act of creating S within T is simply extending that 
definition so that T's new fields start where S's finished. Casting back 
from T should therefore be trivial, but clearly it isn't :-)


I'm sure there's a good reason, but it escapes me at the moment. Any ideas?

Thanks

Chris

-- 
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.


Re: [go-nuts] Error Handling Best Practice (error wrapping)

2018-10-08 Thread Chris Hopkins
{initial long rabley post deleted}

If I understand the exception proposals, they are quite un-go-like. That is 
go as a strongly typed, "no undeclared variables", etc language sits on the 
side of more effort upfront to produce fewer bugs later trade-off. Try ... 
catch however is more of the rough and ready "don't worry about the details 
until I absolutely have to" philosophy.
That's not to say they would be wrong for go, I just got the impression 
exceptions - like interrupts - did not play well with concurrency and large 
projects in general (Except in a "stop the world, I've subbed my toe" kind 
of way).

I can see for many classes of problems they could work very well and 
certainly be convenient, but are they not kind of a "Forget about any 
issues I might have, someone else will fix it" philosophy?

{Hardware Engineer hat on}
I can't help but think that Exceptions in the hardware sense are a costly 
thing, in terms of latency, context switch and the higher level handler 
trying to clean up the state afterwards. In a multi-processor system this 
gets MUCH worse. They are errors in the strictest sense that should be rare.
Perhaps this viewpoint is shading my outlook, of the different concept of 
exceptions here.
{Hat off}

But I think that's what this is, not a question of utility, but of 
philosophy, what type of language do people want go to be? Which scales to 
large systems better? What is easier to understand when someone else has 
written it? 
I guess my fear of a catch type mechanism is coming along to find an 
exception firing in someone else's code and all I see is "Out of Cheese 
error", where that's an error that's used at every place in the code 
anything goes wrong (I joke, but how many times have I seen code that just 
goes log.Fatal("Error")). I could then come along and re-write every one of 
those places to use different errors, but I would hope most people would 
say that that behaviour was bad practice, to be fixed. I believe exceptions 
would encourage, not discourage that behaviour.

Sorry, my short post ended up quite long too!

Regards

Chris
On Monday, 8 October 2018 16:46:28 UTC+1, Robert Engels wrote:
>
> I read the proposal and the only knock against including a stack trace by 
> default is one google problem cited that was clearly bad error handling to 
> begin with. 
>
> Why is there always some need to reinvent the wheel. Leave Go error 
> handling as in and add a throws and catch that new code can use, with the 
> current const based error instances - just add an interface Exception that 
> all throw X need to implement in order to use, and catch on interfaces, not 
> structs. 
>
> On Oct 8, 2018, at 9:54 AM, Chris Hopkins  > wrote:
>
> Thanks. Yes, that's exactly what I want, could I have Go2 now please? ;-)
>
> Okay I'll keep doing it the way I'm doing it with a mind to swapping to 
> that when available.
>
> I had avoided reading the Go2 proposal stuff simply because I regard 
> language design as a question for people with Marvin-like intellects. 
> That's way less scary than the generics proposals that worry me so much.
>
> Thanks again
>
> On Monday, 8 October 2018 15:33:07 UTC+1, Ian Lance Taylor wrote:
>>
>> On Mon, Oct 8, 2018 at 3:38 AM, Chris Hopkins  
>> wrote: 
>> > Hi, 
>> > Could I please check what current error handling best practice is? 
>> > I've gotten quite smitten with github.com/pkg/errors. I really like 
>> the 
>> > ability to create a stack of errors that trace to what is going on. 
>> However 
>> > it seems this is not an often used package - it's not available in 
>> > playground for example. It's really useful for diagnostics to see a 
>> stack of 
>> > what is causing an error, however in my latest application where I'm 
>> trying 
>> > to be really rigorous with my error handling I've hit - for want of a 
>> better 
>> > word - an imperfection. Could I check if there's a better way to do 
>> these 
>> > things: 
>> > So here's what I'm doing: 
>> > When I have an error I need to report I create it like this: 
>> > var ErrInvalidVariable = errors.New("Invalid Variable") 
>> > Which means that you can have code that nicely reads: 
>> > if err == ErrInvalidVariable { /* handle this error */} 
>> > It's how the os package reports errors (along with helper functions), 
>> so I 
>> > assume this is the correct way. 
>> > 
>> > 
>> > For better debug I can use errors.Wrap to annotate this error through 
>> the 
>> > error stack and get useful diagnostic printouts such as 
>> > Line Processing passed "if $BOB==3": Token Passed $BO

Re: [go-nuts] Error Handling Best Practice (error wrapping)

2018-10-08 Thread Chris Hopkins
Thanks. Yes, that's exactly what I want, could I have Go2 now please? ;-)

Okay I'll keep doing it the way I'm doing it with a mind to swapping to 
that when available.

I had avoided reading the Go2 proposal stuff simply because I regard 
language design as a question for people with Marvin-like intellects. 
That's way less scary than the generics proposals that worry me so much.

Thanks again

On Monday, 8 October 2018 15:33:07 UTC+1, Ian Lance Taylor wrote:
>
> On Mon, Oct 8, 2018 at 3:38 AM, Chris Hopkins  > wrote: 
> > Hi, 
> > Could I please check what current error handling best practice is? 
> > I've gotten quite smitten with github.com/pkg/errors. I really like the 
> > ability to create a stack of errors that trace to what is going on. 
> However 
> > it seems this is not an often used package - it's not available in 
> > playground for example. It's really useful for diagnostics to see a 
> stack of 
> > what is causing an error, however in my latest application where I'm 
> trying 
> > to be really rigorous with my error handling I've hit - for want of a 
> better 
> > word - an imperfection. Could I check if there's a better way to do 
> these 
> > things: 
> > So here's what I'm doing: 
> > When I have an error I need to report I create it like this: 
> > var ErrInvalidVariable = errors.New("Invalid Variable") 
> > Which means that you can have code that nicely reads: 
> > if err == ErrInvalidVariable { /* handle this error */} 
> > It's how the os package reports errors (along with helper functions), so 
> I 
> > assume this is the correct way. 
> > 
> > 
> > For better debug I can use errors.Wrap to annotate this error through 
> the 
> > error stack and get useful diagnostic printouts such as 
> > Line Processing passed "if $BOB==3": Token Passed $BOB : Invalid 
> Variable. 
> > 
> > So far so good. This starts to fail though if I'm trying to determine 
> lets 
> > say a fileio error that came from the config file reader, vs the script 
> file 
> > reader. At the moment I can say 
> > _, err := os.Open(...) 
> > if err != nil { 
> >   return errors.Wrap(err, "Config File read error") 
> > } 
> > But without searching through the error text I can't tell who caused 
> that. 
> > Now I could declare a specific type for this, add a Cause handler onto 
> that, 
> > but it starts to get clunky to do that for every error condition. Also 
> it 
> > doesn't scale to more than 2 levels because it stops at the first cause 
> > found. I can obviously work around this, but I'm thinking I'm doing this 
> > wrong, a defining feature of go is the error handling - surely there's a 
> > better way to do it than this!. 
> > 
> > Am I doing something unusual here and wanting to determine where in the 
> > hierarchy of the stack a problem might have come from? How else do 
> people 
> > handle errors in situations like this, where you can't fully handle them 
> > locally, so you want to return the error, but then when you get to the 
> > higher levels you can handle them, as long as you have information about 
> the 
> > error. The annoying thing is, everything is there in the string of the 
> error 
> > message and I could strings.Contains my way through the error string to 
> work 
> > this out, but that feels a really stupid way to do this. 
> > I also come across this in my test cases, I want to inject error to make 
> > sure I am spotting errors correctly and checking that I am getting the 
> > correct error from the correct place is really quite clunky at the 
> moment, 
> > if I could test that an error checker in location X was triggered by it 
> > being passed an error that would save me a lot of code. 
> > 
> > Any suggestions gratefully received. 
>
> Have you seen the error handling thoughts at 
> https://go.googlesource.com/proposal/+/master/design/go2draft.md ? 
> The thoughts about "errors as values" seems relevant here. 
>
> Ian 
>

-- 
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.


[go-nuts] Re: I am not in favor of generics.

2018-09-18 Thread Chris Hopkins
Pondering this, my concern is that it might become too powerful. I'm scared 
this will make it harder to work out what someone has done if there's too 
much indirection and magic added on top. It feels like it could be a really 
*really* big hammer.

I don't buy the argument " those who prefer to avoid generics may do so and 
carry on as they are" because go is all about large projects and code 
reuse. If you enable people to write code that the average programmer can't 
understand, then IMO that is against the philosophy of what i thought go 
was.

Knuth save me from people writing "clever" code.

Chris
On Tuesday, 18 September 2018 12:04:15 UTC+1, alan...@gmail.com wrote:
>
> Although I respect the opinions expressed here, I think you might be 
> pleasantly surprised by how the proposed design would dovetail with the 
> rest of Go and make a number of things much more convenient than they are 
> at present.
>
> It would be nice, for example, to have a full range of collection types in 
> the standard library without the need to use interface{}, type assertions 
> and the performance overhead of 'boxing'. 
>
> It's not an ugly design with angle brackets all over the place and most of 
> the time you'd hardly notice you were using a generic function as the type 
> parameter(s) would be automatically inferred from usage.
>
> Better still it would be compatible with Go 1.
>
> Admittedly, there's a lot of discussion over the design at present though 
> that's mainly about the constraint system. Everybody agrees that this needs 
> to be both simple and  expressive though opinions differ over the best way 
> to achieve that.
>
> Anyway, as I said in another thread, the important thing is that the 
> existing built-in generic stuff is not interfered with, so those who prefer 
> to avoid generics may do so and carry on as they are. That way everybody 
> will be happy :)
>
> Alan
>
> On Monday, September 17, 2018 at 5:04:26 PM UTC+1, 
> jucie@zanthus.com.br wrote:
>>
>> Go core team is working hard to bring generics to the language because 
>> several people asked for it. With all due respect for those users and for 
>> people working hard to make generics a reality, I feel that a greater 
>> number of people would suffer after generics adoption. So, I feel compeled 
>> to manifest my opinion: sorry guys, Go with generics will be worse than Go 
>> without generics.
>>
>> The language strives for simplicity since its inception and that is what 
>> attracted a large part of its user base. We must think about who we will 
>> want to have in our community 10 years from now. Supporting generics would 
>> please a minority to the detriment of a large number of potential users.
>>
>> Today Go is easy to learn and tools are easy to implement. Please keep it 
>> that way.
>>
>> Thanks.
>>
>

-- 
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.


[go-nuts] Re: I am not in favor of generics.

2018-09-18 Thread Chris Hopkins
+1

IMO the place generics would be useful is reducing the use of the empty 
interface and then a type switch. Otherwise I don't see quite what people 
are doing that wouldn't be better done with interfaces.
In the past I mistakenly tried to declare local methods on the builtin 
types. Revisiting my ignorance I wonder if that would help though.

I see the logic that "append and len and other inbuilt functions are 
generic and idiomatic, so it would be better to allow others to write their 
own generic functions". However I would argue that the problem could be 
turned on its head. It's not that other types need to be made more like the 
inbuilts, but that inbuilts become more like all other types. Why doesn't 
append have an interface requirement like the sort interface? 
Anyway I realise I don't understand the problem enough to wrap this up in 
an official proposal, but I see it as it is things like channel operations 
and arithmetic that are unusual and should use interfaces (under the hood), 
rather than everything else fitted around them.

But this is probably me not understanding the problem that people are 
trying to solve. It's more than people wanting to neither use an empty 
interface, nor declare their interfaces isn't it?

Chris
On Monday, 17 September 2018 17:04:26 UTC+1, jucie@zanthus.com.br wrote:
>
> Go core team is working hard to bring generics to the language because 
> several people asked for it. With all due respect for those users and for 
> people working hard to make generics a reality, I feel that a greater 
> number of people would suffer after generics adoption. So, I feel compeled 
> to manifest my opinion: sorry guys, Go with generics will be worse than Go 
> without generics.
>
> The language strives for simplicity since its inception and that is what 
> attracted a large part of its user base. We must think about who we will 
> want to have in our community 10 years from now. Supporting generics would 
> please a minority to the detriment of a large number of potential users.
>
> Today Go is easy to learn and tools are easy to implement. Please keep it 
> that way.
>
> Thanks.
>

-- 
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.


[go-nuts] Re: RFC - Review request for a project done in Golang

2018-05-14 Thread Chris Hopkins
There's an old Dilbert about this:
Don't know how to solve a problem? No problem! Don't hire a consultant; 
hold an interview and choose the best answer you receive from all the 
candidates.

I'll get my coat.

Chris

On Monday, 14 May 2018 12:35:23 UTC+1, Sankar wrote:
>
> Hi
>
> I was recently asked in an interview to write a golang program for a 
> problem that involves working with a million nodes. I did write a program 
> that solved the problem statement. However, I was told that the solution 
> was "poorly structured", but I did not get any detailed review comments 
> though. 
>
> So, I recreated the solution in github and wanted to know if anyone could 
> give some review comments as to what you see as bad things in the code.
>
> The problem statement, code and the instructions are at: 
> https://github.com/psankar/network-monitor 
>
> I personally felt that the code (written in about 6 hours for the 
> interview) is good and I would've hired anyone writing this, but may be I 
> am biased because it is written by me. I want to improve my Golang skills 
> and your review comments would be helpful. Any help ?
>
> If the golang list is unsuitable for this, you can even email me, 
> individually, with the review comments.
>
> Thanks.
>
> Sankar
>

-- 
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.


[go-nuts] Re: constructors vs lazy initialization

2018-03-05 Thread Chris Hopkins
I would say Lazy initialisation should build code that is more robust - I 
can think of few applications where that is not worth the price. So as a 
rule I agree Lazy is a good place to start unless you have a good reason 
not to. I also understood it was more idiomatic.

In terms of reading/debugging, intuitively I prefer constructors as it 
removes the need for every actor to do the check.  If you have a large 
number of methods you get a lot of repeated code. Also there will be a 
small cost to doing the check, so for performant code I would lean towards 
that.
However I did profile this once for a particular problem I was working on 
and found Lazy more performant, possibly because of the zero initialisation 
effect (not doing work twice), or maybe because the workload was spread out 
between threads and therefore the contents of the cache line was local - I 
never did get to the bottom of it. I did also wonder if Go is able to use 
the feature present in a lot of modern Caches where you can mark a line as 
Zero and the cache will never bother to fetch it from memory, saving power 
and improving latency.

It's taken me a while to come to this viewpoint as being a hardware 
engineer I'm suspicious of Go's policy of zeroing a struct at 
initialisation. "Surely", I would argue, "good software will always write a 
variable before it is read. If it reads before write then it is bad 
software and it's better to find that out sooner." I know that I am 
provably wrong on this, but still it *feels* like bad practice even if it 
isn't.

The reason I developed such a dislike for default zero-ing is I was 
simulating the boot up of a processor, 1ms of processor time took about 30 
minutes to run. I discovered that something like 2 hours of of each 
simulation was being lost due to the boot code zeroing a block of memory 
before using it for the stack. i.e. memory that was almost guaranteed to be 
written before being read. A little more digging and overall something like 
6 hours of the 12 hour simulation was spent in memset0. 
Traumas from your youth: They cloud your thinking for the rest of your life 
:-)


Chris
On Sunday, 4 March 2018 00:37:43 UTC, Anmol Sethi wrote:
>
> How do you guys choose between constructors and lazy initialization?
>
> For example.
>
> Struct constructors:
>
> type meow struct {
> x http.Handler
> }
>
> func newMeow() *meow {
> return {
> x: http.NewServeMux(),
> }
> }
>
> func (m *meow) do() {
> // stuff
> }
>
>
> Lazy initialization:
>
> type meow struct {
> x http.Handler
> }
>
> func (m *meow) do() {
> if m.x == nil {
> m.x = http.NewServeMux()
> }
> // stuff
> }
>
>  

-- 
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.


[go-nuts] Re: All Forms of Wishful Generics

2018-02-19 Thread Chris Hopkins

>
> I think everybody here is aware that some people really want generics and 
> that generics would probably be useful for everybody. Instead of restating 
> that why not share what you think about this version of Go generics?
>
> IMO this is not a proven statement.
One of the things that for me I like about Go is that one can read code and 
reason about its behaviour to a reasonable extent.  In my very limited 
experience generics would make it considerably more difficult to reason 
about exactly what a piece of code will do.
While generics would allow some problems to be expressed in a simpler 
fashion, I'm not convinced that that would produce a more comprehensible 
code-base. I really worry they would just facilitate lazy programming where 
people save a few keystrokes at the expense of: "You too need a brain the 
size of a planet, like mine, to understand this."

Maybe this is unfounded, but I'm far from convinced that generics would 
make my experience of Go better. I'm really thinking here of, are we really 
sure they would make large unfamiliar codebases more comprehensible? Every 
feature of a language can be abused, so are they worth the abuse that they 
would allow?

Chris

-- 
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.


[go-nuts] Re: Tweaking sync.Pool for mostly-empty pools

2018-02-19 Thread Chris Hopkins
I would have expected the compiler to allowed to change:
if len(l.shared) > 0 { # the racy check for non-emptiness
  l.Lock()
  last := len(l.shared) - 1
to
tmp := len(l.shared)
if tmp > 0 { # the racy check for non-emptiness
  l.Lock()
  last := tmp - 1

I'd be interested if this were a legal optimisation. Were it so, then you 
could get illegal behaviour.

Maybe?

Chris


On Friday, 16 February 2018 14:57:59 UTC, Carlo Alberto Ferraris wrote:
>
> Also, keep in mind, "being there nothing in the pool" is the common state 
> of pools immediately after every GC.
>
> On Friday, February 16, 2018 at 12:05:27 PM UTC+9, Kevin Malachowski wrote:
>>
>> If there is likely nothing in the Pool, then maybe it's better to not use 
>> one at all. Can you compare the internal workload with an implementation 
>> where all callers just call the `New` function directly? What's the purpose 
>> of using a pooled memory if there's often nothing in the pool?
>>
>> On Wednesday, February 14, 2018 at 3:56:34 PM UTC-8, Carlo Alberto 
>> Ferraris wrote:
>>>
>>> In an attempt to reduce the time pprof says is spent in sync.Pool 
>>> (internal workloads, sorry) I modified Get and getSlow to skip locking the 
>>> per-P shared pools if the pools are likely to be empty. This yields 
>>> promising results, but I'm not sure the approach is sound since the check I 
>>> do is inherently racy.
>>>
>>> As a (artificial and contrived) benchmark, I'm using this:
>>>
>>> func BenchmarkPoolUnderflow(b *testing.B) {
>>>   var p Pool
>>>   b.RunParallel(func(pb *testing.PB) {
>>> for pb.Next() {
>>>   p.Put(1)
>>>   p.Get()
>>>   p.Get()
>>> }
>>>   })
>>> }
>>>
>>> This is meant to simulate a pool in which more or objects are Get() than 
>>> are Put() (it wouldn't make much sense to simulate a pool in which we only 
>>> get, so to keep things simple I opted for a 2:1 ratio)
>>>
>>> The change I applied to Get and getSlow is the following. Starting from 
>>> the current pattern of:
>>>
>>> l := ... # per-P poolLocal
>>> l.Lock()
>>> last := len(l.shared) - 1
>>> if last >= 0 {
>>>   x = l.shared[last]
>>>   l.shared = l.shared[:last]
>>> }
>>> l.Unlock()
>>>
>>> I add a check (not protected by the mutex, that is the expensive op 
>>> we're trying to skip if it's not necessary) to see if the pool is likely to 
>>> be non-empty: 
>>>
>>> l := ... # per-P poolLocal
>>> if len(l.shared) > 0 { # the racy check for non-emptiness
>>>   l.Lock()
>>>   last := len(l.shared) - 1
>>>   if last >= 0 {
>>> x = l.shared[last]
>>> l.shared = l.shared[:last]
>>>   }
>>>   l.Unlock()
>>> }
>>>
>>> I know I should not call this a benign race, but in this case I don't 
>>> see how this can lead to problems. If the racy check gets it right, then 
>>> it's almost a net win. If if it gets it wrong, either we do what we do now 
>>> (i.e. we lock, just to find an empty pool), or we skip an otherwise 
>>> non-empty pool - thereby failing to immediately return an otherwise 
>>> reusable object (note that 1. there is a per-P shared pool for each P, so 
>>> I'd estimate the chances of this happening on all of them to be pretty low 
>>> and 2. the Pool documentation explicitly say that Get is allowed to treat 
>>> the pool as empty). Also note that the race detector is already explicitly 
>>> disabled in all sync.Pool methods.
>>>
>>> The reason I'm asking is to understand whether my reasoning is sound 
>>> and, regardless, if anybody has suggestions about how to do this in a 
>>> better way.
>>>
>>> The current results (of the approach above, plus some refactoring to 
>>> recover some lost performance on the other benchmarks) on my laptop are the 
>>> following:
>>>
>>> name old time/op  new time/op  delta
>>> Pool-4   14.5ns ± 3%  14.2ns ± 2%   -1.64%  (p=0.023 n=9+10)
>>> PoolOverflow-4   1.99µs ±12%  1.78µs ± 1%  -10.62%  (p=0.000 n=10+8)
>>> PoolUnderflow-4   152ns ± 6%30ns ± 1%  -80.00%  (p=0.000 n=10+8)
>>>
>>> (the first two benchmarks are already part of sync.Pool, the last one is 
>>> the one I described above)
>>>
>>> Any feedback is welcome. If this is deemed safe I'm going to submit a CL.
>>>
>>> Carlo
>>>
>>>
>>>

-- 
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.


Re: [go-nuts] Re: GOTCHA: Just when you think you understand interfaces

2018-02-05 Thread Chris Hopkins
Well, the first allows one Less per package, the second allows one per 
type. Since I tend to have multiple types in a package I find that more 
readable.

Anyway, I finally fixed the problem with mixture of reflect and type 
assertion
  val := reflect.ValueOf(b)
  if val.Kind() == reflect.Slice {
leng = val.Len() // outer length
for i := 0; i < leng; i++ {
  v := val.Index(i)
  if v.Kind() == reflect.Slice {
sz = v.Len() // inner length
for j := 0; j < sz; j++ {
  vv := v.Index(j)
if m, ok := vv.Interface().(Useable); ok {
n, ok := 
reflect.ValueOf(a).Index(i).Index(j).Interface().(Useable)
if !ok {
  log.Fatal("a is not the same type as b")
}
good = m.Equal(n)
  } else {
log.Fatal("Candidate cannot be converted to a Usable type")
  }
}
  }
}
  }


Yeah it's a bit ugly and I'm working on something better, but the immediate 
issue is closed for now, so thanks everyone for the kick in the right 
direction.

Regards

Chris


On Thursday, 1 February 2018 18:55:27 UTC, Axel Wagner wrote:
>
> I don't really see the difference in writing
> func Less(a, b *T) bool
> and
> func (a *T) Less(b *T) bool
> convenience wise - except that the latter requires the name to be exported 
> and doesn't allow using a function literal (so, yeah, the latter actually 
> seems significantly *less* convenient).
>
> On Thu, Feb 1, 2018 at 7:51 PM, Chris Hopkins <cbeho...@gmail.com 
> > wrote:
>
>> No, was hoping to use the interface (It's the only reason I defined it) 
>> to test if two items are equal.
>> I guess I could enforce that you have to supply the equals function like 
>> the sort interface does. I was just hoping for more.
>>
>> I'll have a rethink next time I have time.
>>
>> Thanks
>>
>> On Thursday, 1 February 2018 18:46:09 UTC, Axel Wagner wrote:
>>>
>>> On Thu, Feb 1, 2018 at 11:52 AM, Chris Hopkins <cbeho...@gmail.com> 
>>> wrote:
>>>
>>>> Yeah, so having played with this. It seems that this is going to take 
>>>> some judicious use of reflect if I'm to stand any chance of maintaining a 
>>>> flexible API, which I really hoped to avoid.
>>>>
>>>
>>> I'm 99% sure that you don't have to use reflect at all. You only have to 
>>> swap elements around, that's kind of what sort.Interface was made for. It 
>>> already comes with implementations for slices of common datatypes and you 
>>> can make a function that works on arbitrary slices with less than ten lines 
>>> of reflect code.
>>>
>>> Like, I *really* don't understand your problem.
>>>  
>>>
>>>> I had assumed that the point of interfaces was to avoid this. I guess 
>>>> from a high level I don't see why a slice of type is really that different 
>>>> from a type. But I have never written a compiler so I'm sure that it's way 
>>>> more complex than it seems. :-)
>>>>
>>>> Thanks for the help.
>>>> Chris
>>>>
>>>>
>>>> On Thursday, 1 February 2018 00:42:04 UTC, simon place wrote:
>>>>>
>>>>> also notice, if you haven’t encountered it, this makes []interfaces a 
>>>>> bit awkward to handle with ellipsis functions...
>>>>>
>>>>> https://play.golang.org/p/JWuc4jt2uSP
>>>>>
>>>>> what i do is this; 
>>>>>
>>>>> https://play.golang.org/p/O9Q4K_vXlul
>>>>>
>>>>> but you will need a convert for all combinations of interfaces and 
>>>>> ellipsis functions you have!
>>>>>
>>>>> from what i understand ellipsis functions are implemented simply as 
>>>>> auto-magic slices, rather than expanded out, so the function doesn’t 
>>>>> apply 
>>>>> the interface wrapping like with individual parameters.
>>>>>
>>>>> -- 
>>>> 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.
>>>> For more options, visit https://groups.google.com/d/optout.
>>>>
>>>
>>> -- 
>> 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 .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

-- 
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.


Re: [go-nuts] Re: GOTCHA: Just when you think you understand interfaces

2018-02-01 Thread Chris Hopkins
No, was hoping to use the interface (It's the only reason I defined it) to 
test if two items are equal.
I guess I could enforce that you have to supply the equals function like 
the sort interface does. I was just hoping for more.

I'll have a rethink next time I have time.

Thanks

On Thursday, 1 February 2018 18:46:09 UTC, Axel Wagner wrote:
>
> On Thu, Feb 1, 2018 at 11:52 AM, Chris Hopkins <cbeho...@gmail.com 
> > wrote:
>
>> Yeah, so having played with this. It seems that this is going to take 
>> some judicious use of reflect if I'm to stand any chance of maintaining a 
>> flexible API, which I really hoped to avoid.
>>
>
> I'm 99% sure that you don't have to use reflect at all. You only have to 
> swap elements around, that's kind of what sort.Interface was made for. It 
> already comes with implementations for slices of common datatypes and you 
> can make a function that works on arbitrary slices with less than ten lines 
> of reflect code.
>
> Like, I *really* don't understand your problem.
>  
>
>> I had assumed that the point of interfaces was to avoid this. I guess 
>> from a high level I don't see why a slice of type is really that different 
>> from a type. But I have never written a compiler so I'm sure that it's way 
>> more complex than it seems. :-)
>>
>> Thanks for the help.
>> Chris
>>
>>
>> On Thursday, 1 February 2018 00:42:04 UTC, simon place wrote:
>>>
>>> also notice, if you haven’t encountered it, this makes []interfaces a 
>>> bit awkward to handle with ellipsis functions...
>>>
>>> https://play.golang.org/p/JWuc4jt2uSP
>>>
>>> what i do is this; 
>>>
>>> https://play.golang.org/p/O9Q4K_vXlul
>>>
>>> but you will need a convert for all combinations of interfaces and 
>>> ellipsis functions you have!
>>>
>>> from what i understand ellipsis functions are implemented simply as 
>>> auto-magic slices, rather than expanded out, so the function doesn’t apply 
>>> the interface wrapping like with individual parameters.
>>>
>>> -- 
>> 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 .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

-- 
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.


[go-nuts] Re: GOTCHA: Just when you think you understand interfaces

2018-02-01 Thread Chris Hopkins
Yeah, so having played with this. It seems that this is going to take some 
judicious use of reflect if I'm to stand any chance of maintaining a 
flexible API, which I really hoped to avoid.
I had assumed that the point of interfaces was to avoid this. I guess from 
a high level I don't see why a slice of type is really that different from 
a type. But I have never written a compiler so I'm sure that it's way more 
complex than it seems. :-)

Thanks for the help.
Chris

On Thursday, 1 February 2018 00:42:04 UTC, simon place wrote:
>
> also notice, if you haven’t encountered it, this makes []interfaces a bit 
> awkward to handle with ellipsis functions...
>
> https://play.golang.org/p/JWuc4jt2uSP
>
> what i do is this; 
>
> https://play.golang.org/p/O9Q4K_vXlul
>
> but you will need a convert for all combinations of interfaces and 
> ellipsis functions you have!
>
> from what i understand ellipsis functions are implemented simply as 
> auto-magic slices, rather than expanded out, so the function doesn’t apply 
> the interface wrapping like with individual parameters.
>
>

-- 
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.


Re: [go-nuts] GOTCHA: Just when you think you understand interfaces

2018-01-31 Thread Chris Hopkins
Okay well the actual (working version) of the code (before I wrote the test 
cases that are currently failing/not compiling) is here (I refuse to check 
in broken code):
https://github.com/cbehopkins/permutation/blob/master/helpers.go

The source library (permutation) can cope with permutes on arrays of 
arbitrary type as long as you supply a Less function. I'm trying to extend 
the test cases so anything other than int type is tested.
I've long preached that is you're using reflect you're probably doing it. I 
know the source library uses reflect for these things, I'm trying to avoid 
it.

I just can't see a different way to do it.

Thanks
Chris

On Wednesday, 31 January 2018 17:46:51 UTC, Axel Wagner wrote:
>
> FTR, you can also pass an actual []Usable, instead of a []tmpType. That is 
> do
> https://play.golang.org/p/N_CJh0Ekik8
> But I do think that your code and question suggest that you are trying to 
> use interfaces to do some sort of subtyping, which is just not how they are 
> supposed to be used.
>
> On Wed, Jan 31, 2018 at 6:43 PM, Axel Wagner <axel.wa...@googlemail.com 
> > wrote:
>
>> You have to use reflection for that. Go doesn't have subtyping of that 
>> kind. This smells a bit of an xy-problem <http://xyproblem.info/> to me, 
>> though. There are several things here, that suggest an antipattern going 
>> on. With a little bit of context on the actual problem you are trying to 
>> solve, we might be able to come up with a more idiomatic design.
>>
>> On Wed, Jan 31, 2018 at 6:37 PM, Chris Hopkins <cbeho...@gmail.com 
>> > wrote:
>>
>>> Hi
>>> Sharing my ignorance:
>>> I didn't realise that although you can switch-case on an interface, an 
>>> array of interfaces doesn't work.
>>> https://play.golang.org/p/tD8msjCXyuZ
>>>
>>> Any ideas on how to cope with this? I tried:
>>> _, ok = tmp.([]Useable)
>>>
>>> But that fails for the same reason. I can't work out how to detect if 
>>> the type (of the empty interface) is an array of a type that satisfies the 
>>> (useful) interface.
>>> This must be a common problem and PEBKAC surely?
>>>
>>> Regards
>>>
>>> Chris
>>>
>>> -- 
>>> 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 .
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>>
>>
>

-- 
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.


[go-nuts] GOTCHA: Just when you think you understand interfaces

2018-01-31 Thread Chris Hopkins
Hi
Sharing my ignorance:
I didn't realise that although you can switch-case on an interface, an 
array of interfaces doesn't work.
https://play.golang.org/p/tD8msjCXyuZ

Any ideas on how to cope with this? I tried:
_, ok = tmp.([]Useable)

But that fails for the same reason. I can't work out how to detect if the 
type (of the empty interface) is an array of a type that satisfies the 
(useful) interface.
This must be a common problem and PEBKAC surely?

Regards

Chris

-- 
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.


[go-nuts] gofmt rewrite rules

2018-01-23 Thread Chris Hopkins
Hi,
I'm tidying up some code and I think this would be a great use for gofmt's 
rewrite capabilities, but I can't make it work. I have some code where 
error checking is missing.
In the code every instance of Set returns an error value that is not 
checked, so I assumed I could write:

gofmt -w -r 'a.Set(b,c) -> err:=a.Set(b,c)\nif err != nil{log.Fatal("Set 
Error",err)}'

and (for example) this would change:
x.Set(bob,fred)
to:
err := x.Set(bob,fred)
if err != nil{log.Fatal("Set Error",err)}

(Actual error handling removed for simplicity of example)

Before I crack out sed or perl, any suggestions for if this is possible the 
"correct" way?

In a follow up question, I've come across go IDEs which allow you to do 
things like automatically rename handler receivers to be consistent across 
a type. Unfortunately it doesn't seem to be possible to do this with gofmt 
out of the box, as rewrite rules can't target specific types that I know 
of. Is this actually possible?

I guess a further question is, while I have found some examples of gofmt 
rules, they seem to be quite thin on the ground, is anyone aware of a good 
collection of examples?

Regards

Chris

-- 
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.


Re: [go-nuts] study go package

2018-01-19 Thread Chris Hopkins
Agreed.
I found the standard library and ioutil in particular a good start. YMMV.

On Friday, 19 January 2018 13:03:52 UTC, Gianguido Sorà wrote:
>
> I think that the Go source code itself is among the best sources of good 
> practices and well-written Go. 
>
> Il 19 gen 2018 13:52, "Keith Brown"  ha 
> scritto:
>
>> I want to pick up good practices when developing my go code. Is there a 
>> package which I can study and comprehend for newbies? I mainly use 
>> effective go but would like to see more examples of good software/code 
>> design layout. 
>>
>> BTW, in Python I always followed twisted as my examples for testing, code 
>> layout,etc...
>>
>>
>> -- 
>> 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 .
>> For more options, visit https://groups.google.com/d/optout.
>>
>

-- 
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.


[go-nuts] Non-Coherent Caches

2018-01-12 Thread Chris Hopkins
Hi All,
Does anyone know of an architecture that go runs on that has non-coherent 
data caches? If so, is there a mechanism in the language/tool chain to 
protect against the issues of this?

Background:
I was watching a video on the go trace tool 
(https://www.youtube.com/watch?v=ySy3sR1LFCQ) in this video he uses a 
technique I would never have thought safe. i.e. he declares an array of 
items and then uses a separate go routine on each item in the array. The 
logic making it safe being that each routine operates on a different 
element of the array, therefore no concurrent access.
Then it occurred to me it might not be safe after all. If you have 
Non-Coherent data caches for multiple cores then one cache could load a 
cache line and modify it. At a similar time a different cache does the same 
thing, but to a different address within that cache line. One of them 
evicts the line first, and its modification is overwritten by the last 
cache to have the line modified.

Some digging shows that all the CPU architectures I can find that I can run 
go on have coherent L1 data caches.

However I set out to prove this was safe:
https://play.golang.org/p/igfpqrX8Jc-

Playing with the trace tool implies that this might be because I can't get 
the scheduler to launch multiple routines running at the same time (hence 
adding in the heavyCpu function). Or at least sufficiently concurrent to 
agress this issue.
So it's fine, but it got me wondering if it were fine by accident or 
design. I'm sure there must be architectures out there where global 
coherency across all cores is not maintained, and if there is, I guess the 
scheduler would have to be aware of this - but I don't know how you could 
mitigate this if the example code is legal. If it is not legal, it doesn't 
seem to be detected by the tools.

Anyway thought I would share my ignorance again :-)

Regards

Chris

-- 
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.


Re: [go-nuts] Using database/sql in a web application

2018-01-05 Thread Chris Hopkins
Why not use an interface?
type TableSaver func (db *DB)
or 
type TableSaver func (tx *Tx) // depending on your needs


Allowing you to:
func (t *Table) SaveTable (...) {}


Which in your example if you wanted use a different SaveTable  
implementation for OtherTable you could. Otherwise it would just inherit it 
from Table.
Or am I missing something here?

Chris

On Friday, 5 January 2018 16:11:53 UTC, Manlio Perillo wrote:
>
> Il giorno venerdì 5 gennaio 2018 16:57:04 UTC+1, Ayan George ha scritto:
>>
>>
>>
>> On 01/05/2018 10:16 AM, Manlio Perillo wrote: 
>> > Recently I have developed a few web applications in Go, using a 
>> > PostgreSQL database, but I have yet understand the best way to use 
>> > the database/sql package. 
>> > 
>>
>> I don't know how you're serving web pages but I typically use net/http. 
>> This also means that I typically build an http.Server.  This requires 
>> that I create a type that conforms to the http.Handler interface. 
>>
>
> Yes, I use the standard net/http interface, without frameworks (but I use 
> a simple toolkit written by me).
>
>>
>> You can use this type to pass around all of the data you need, including 
>> sql.DB instances, log.Logger, etc. 
>>
>> So here's the skeleton of what I normally do.  I haven't tested this -- 
>> this is just to get the point across.  Finally, this may be completely 
>> off base.  I'm open to any criticisms etc. anyone may have. 
>>
>> package main 
>>
>> import ( 
>>   "database/sql" 
>>   _ "github.com/lib/pq" 
>>   "log" 
>>   "net/http" 
>>   "time" 
>> ) 
>>
>> type app struct { 
>>   db *sql.DB 
>> } 
>>
>> func (a *app) ServeHTTP(w http.ResponseWriter, r *http.Request) { 
>>   // here we can use all of the fields of our app struct -- including 
>> the db! 
>>
>>   row := db.QueryRow("select current_timestamp;") 
>>
>>   var time string 
>>   err := row.Scan() 
>>
>>   if err != nil { 
>> // handle the error.  maybe log it?  i typically 
>> // create a log.Logger instance in my app and use it 
>> // at times like these. 
>> return 
>>   } 
>>
>>   w.Write([]byte("hello, world!")) 
>> } 
>>
>> func main() { 
>>   db, err := sql.Open("postgres", "...") 
>>
>>   if err != nil { 
>> log.Fatal(err) 
>>   } 
>>
>>   if err := db.Ping(); err != nil { 
>> log.Fatal(err) 
>>   } 
>>
>>   myapp := app{ 
>> db: db, 
>>   } 
>>
>>   srv := http.Server{ 
>> Addr: ":8080", 
>> ReadTimeout:  1 * time.Second, 
>> WriteTimeout: 1 * time.Second, 
>> Handler:  , 
>>   } 
>>
>>   log.Fatal(srv.ListenAndServe()) 
>> } 
>>
>
> Thanks, this is  a very good solution.
>
> Currently I'm using something different, however.
> I have a package that exports the same API as database/sql, but as free 
> functions using a global *DB configured when loading a configuration file.
>
> However the question is the same, and it is how and what to pass to 
> functions that need a connection to the database.
>
> Passing *DB is no good; take as an example a "generic" package having
>
>   type Table struct {
>   A int
>   B string
>   }
>
>   func SaveTable(t *Table, db *DB) ...
>
> or
>   func SaveTable(t *Table, tx *Tx) ...
>
> The function does not need to know if it is inside a transaction; it is 
> the responsibility of the caller.
>
> However consider a package with
>
>   type Table struct {
>   A int
>   B string
>   }
>
>   type OtherTable struct {
>   Table
>   C float64
>   B bool
>   }
>
>
> Now the function SaveOtherTable may want to use a transaction to save 
> Table and OtherTable separately.
> You surely can not pass a *Tx, since it does not support nested 
> transactions.
>
>
>
> Thanks
> Manlio Perillo
>
>
>

-- 
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.


[go-nuts] Compiler Static Optimisation

2017-12-19 Thread Chris Hopkins
Hi,
I assume this is expected behaviour to most, but it went against my 
expected behaviour so thought I would share.
I was benchmarking some code and in the inner loop discovered that:

if true {
  funcA()
} else {
  funcB()
}


was slower than:
//if true {
  funcA()
//} else {
//  funcB()
//}


On the one hand: DUH! of course.
On the other I expected these kind of basic compile time optimisations to 
be a thing.

So I assume the Go compiler doesn't try and do this analysis in a Compile 
time vs Execution time tradeoff. It may also be that the compiler does try 
and do this, but it didn't recognise it in my code.

Anyway Hope that is useful to someone. It has certainly changed the way I 
will write my (profiled) inner loops.

Chris

-- 
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.


Re: [go-nuts] Re: Go Compiler How Work?!

2017-12-13 Thread Chris Hopkins


On Wednesday, 13 December 2017 12:40:18 UTC, erfang...@gmail.com wrote:
>
> How can write a compiler Using C as test.exe then can use from test.exe 
> compiler any where... so can write a input file like hello world 
> application and generate executable file using test.exe.
>
> the compiler is told what to target so rather than translate 

a = a + b
into e.g.
ADD R0, R0, R1  # the ASM for architecture A
it instead translates it to:
ADS R0,R1 # ASM for architecture B

That's all it is doing in the end, translating text from one form into 
another



-- 
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.


Re: [go-nuts] Re: Go Compiler How Work?!

2017-12-13 Thread Chris Hopkins


On Wednesday, 13 December 2017 12:35:17 UTC, erfang...@gmail.com wrote:
>
> i am not tell interpreter.
>

I'm not sure if you mean interpreter here in the context of interpreted 
language, or interpreter, someone  who translates between human languages.
 

> i am tell compiler for generate a cross executable file.
> may be show me a *tutorial*/video or a sample small compiler Using C 
> Without Assembly?
>

Right, so this isn't about Go specifically.
This seems to be about how a program on one system can build a program on 
another. The answer to that question is exactly the same as how a compiler 
takes text and produces ASM to run on itself.
There are tons of videos on youtube about this. Just search Compiler 
theory. Or if you prefer the breakthrough for me was understanding ASTs 
(Abstract Syntax Trees)

Assuming that is what you don't understand.

-- 
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.


Re: [go-nuts] Re: Go Compiler How Work?!

2017-12-13 Thread Chris Hopkins
I think we have a misunderstanding. If we don't clear up this 
misunderstanding then we will keep going around in circles. 
Not wishing to offend, this comes across as a fishing expedition not as a 
request for specific help; however under the assumption that this is not 
the case, I'll try and guess at what you mean.

"how can make a new compiler programming language using c without assembly?"

Forget C. There is nothing special about C. It's just a computer language 
like any other. Any language can be used to create a compiler, you are 
converting text into an AST then resolving that.
The question I think you are asking is:
"how can make a new compiler programming language using an existing 
language?"
or
"How can you write a program that will convert Text into Assembly?"

If this is what you are asking, then you are fundamentally asking me to 
describe how a compiler works, in the length of an email. There are books 
thousands of pages long written on this subject.
Before I even start to tackle that, can I confirm this is what you are 
asking?

Regards

Chris
On Wednesday, 13 December 2017 12:20:22 UTC, erfang...@gmail.com wrote:
>
> Could you first answer this question?
> They question may also be answered.
>
> *how can make a new compiler programming language using c without 
> assembly?(a compiler then can produce executable file) ??*
>
> On Wednesday, December 13, 2017 at 3:40:05 PM UTC+3:30, Chris Hopkins 
> wrote:
>>
>> Before I answer anything else, I don't understand what you are saying 
>> with:
>>
>> On Wednesday, 13 December 2017 11:49:06 UTC, erfang...@gmail.com wrote:
>>>
>>> i want research about gocompiler and want recompile main go-compiler in 
>>> gnu/linux operation system.(ubuntu/arch)
>>> not recompile golang.
>>>
>>
>> To my mind:
>> golang == gocompiler
>>
>> (Yes one could argue golang is also the go tooling + the standard library 
>> + the open sourced packages + the community + ... but that's beside the 
>> point)
>>
>> What do you mean by the differences between "main go-compiler" and 
>> "golang"
>>
>> Regards
>>
>> Chris
>>
>

-- 
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.


Re: [go-nuts] Re: Go Compiler How Work?!

2017-12-13 Thread Chris Hopkins
Before I answer anything else, I don't understand what you are saying with:

On Wednesday, 13 December 2017 11:49:06 UTC, erfang...@gmail.com wrote:
>
> i want research about gocompiler and want recompile main go-compiler in 
> gnu/linux operation system.(ubuntu/arch)
> not recompile golang.
>

To my mind:
golang == gocompiler

(Yes one could argue golang is also the go tooling + the standard library + 
the open sourced packages + the community + ... but that's beside the point)

What do you mean by the differences between "main go-compiler" and "golang"

Regards

Chris

-- 
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.


Re: [go-nuts] Re: Go Compiler How Work?!

2017-12-13 Thread Chris Hopkins
You keep asking the same question, I think we have a misunderstanding here. 
To grossly simplify:

Way back when, the first C compilers were written in Assembly. Then someone 
produced a C compiler that was written in C. Now you use a C compiler to 
build a C compiler.
Some time ago the go compiler was written in C. Then someone produced a Go 
compiler that was written in Go. Now you use a Go compiler to build a Go 
compiler.

In the same way you can compile a C compiler with a C compiler, now once 
you have a Go compiler you can make a new Go compiler.
Yes, you need a C compiler to make the very first Go compiler, but you also 
need a C compiler to make a C compiler. Unless you have the very first C 
compiler that was written in Assembler.*

But you now have an assembly version of the Go compiler for all popular 
platforms. So you can just download that,
If you want it for an unpopular platform, then cross-compile.
If you don't want to do that, then use a C compiler to build an early 
version of the Go compiler; then use that to build a modern version of the 
go compiler.

Does that make sense?

* I believe the actual first C compiler was written in another language, 
but as I'm a hardware engineer, not a software historian :-)

Chris

On Wednesday, 13 December 2017 11:30:53 UTC, erfang...@gmail.com wrote:
>
> ?!! how may be?
> a software , for this then generate a binary file. need Asm or 
> Assembler or another Compiler.
>
> if gocompiler not use c-compiler for generate binary file.(for a test 
> hello world golang appliaction)
>
> so GoCompiler how generate binary file for any platform?!
>
> may be explain me how gocompiler work?!
>
> On Wednesday, December 13, 2017 at 4:41:03 AM UTC+3:30, Bruno Albuquerque 
> wrote:
>>
>> No the compiler does not generate C code. The compiler compiles Go code 
>> to the actual final binary.
>>
>

-- 
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.


[go-nuts] Re: goimports build problems "undefined: doTrace"

2017-10-03 Thread Chris Hopkins
Ah, thanks I was using build in an attempt to reduce the scope of the 
problem (under the assumption that one of the things that install did under 
the hood was call build).
(Also it's habit to test things locally before installing them and 
overwriting the tool I am depending on with a broken version I now can't 
get rid of!)

Cool that works now, many thanks. 
*runs some tests*
Interesting I was under the misapprehension that install wouldn't work if 
there were multiple files with a main function in a single package - that 
install could only cope with a single thing at once.
Why do I ever assume that go would do anything other than the sensible & 
clever thing?

Thanks!

Chris


On Tuesday, 3 October 2017 10:07:58 UTC+1, Dave Cheney wrote:
>
> go build works with packages, not files. In this instance you want (from 
> that directory)
>
> go build ./goimports
>
> May I humbly suggest go install -v, rather than go build. 
>
>

-- 
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.


Re: [go-nuts] Errors out of syscall

2017-10-02 Thread Chris Hopkins
Thanks, that's really useful.
It never occurred to me that you could cast it to a type after the error 
has been appended - my attempts to print out the type that was being 
returned didn't show this as an option.

I'll have a play.

Thanks again

On Monday, 2 October 2017 17:20:41 UTC+1, Marvin Renich wrote:
>
> * Marvin Renich <mr...@renich.org > [171002 11:31]: 
> > * Chris Hopkins <cbeho...@gmail.com > [171002 10:52]: 
> > >   out, err := os.Create(potential_file_name) 
> > >   switch t := err.(type) { 
> > >   case *os.PathError: 
> > > switch t.Err { 
> > > case os.ErrNotExist: 
> > >   log.Fatal("Invalid filename", potential_file_name) 
> > > case os.ErrInvalid: 
> > >   log.Fatal("Invalid argument", potential_file_name) 
> > > default : 
>
> Additionally, os.Create, os.Open, and os.OpenFile all guarantee (via 
> their documentation and the Go 1 Compatibility Guarantee) that if they 
> return a non-nil error, it will be of type *os.PathError, so you could, 
> if you wish, replace the "switch t := err.(type)" with 
> t = err.(*os.PathError) and if it panics, you can file a bug. 
> Furthermore, because the current implementation is extremely unlikely to 
> change, you can simplify even more.  I would write this as: 
>
> var out, err = os.Create(potential_file_name) 
> if err != nil { 
> var pe = err.(*os.PathError) // let it panic or use the ,ok trick 
> as below 
> var en, ok = pe.Err.(syscall.Errno) // not a Go 1 Compat 
> guarantee, so handle failed type assertion 
> if !ok { 
> log.Fatalf("Unexpected error from os.Create: %s\n", pe) 
> } 
> switch en { 
> case syscall.EEXIST: 
> ... 
> case syscall.EISDIR: 
> ... 
> case syscall.EINVAL: 
> ... 
> } 
> } 
>
> This code is much more readable than the nested type switch that you are 
> using.  Note that os.ErrNotExist and os.ErrInvalid are not of type 
> *os.PathError and os.Create will never return either of them (promised 
> by Go 1 Compat). 
>
> If the !ok test ever succeeds, you know that the implementation of 
> os.OpenFile has changed. 
>
> ...Marvin 
>
>

-- 
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.


Re: [go-nuts] Errors out of syscall

2017-10-02 Thread Chris Hopkins
Sorry I was showing a code fragment as the actual code is a bit rubbish!
Truncated version at the end, but the point was that  it was an error of 
type *os.PathError. It appears that the os package is creating a new error:
https://golang.org/src/os/file_unix.go?s=4493:4559#L170
based upon the return from the syscall. This obscures the actual source of 
the error and means the only way of interpreting the cause of the error is 
to parse the string.

I get that os specific things like file system errors are going to be very 
os specific, but is this really our only option? Could we not pass the 
error value through the Wrap method Dave suggests? Could these errors not 
have error types we could inspect? Could some of these error types "File 
already exists", "Cannot create file, already exists and is a directory" 
etc that will be common across OSs be collected into come common error 
types. That will never catch them all, but if the common ones can be caught 
it's got to reduce the effort of handling this stuff.

Regards
-

  out, err := os.Create(potential_file_name)
  switch t := err.(type) {
  case *os.PathError:
switch t.Err {
case os.ErrNotExist:
  log.Fatal("Invalid filename", potential_file_name)
case os.ErrInvalid:
  log.Fatal("Invalid argument", potential_file_name)
default :
switch t.Err.Error(){
case "is a directory":
  // Case we are trying to catch
  return
default:
  log.Fatalf("Unknown 
os.PathError\n\"%s\"\n%v\n,Type:%t\nDir:%s\nUrl:%s\n", potential_file_name, 
t.Err, t.Err, dir_str, fetch_url)
  }
}
  case nil:
// nothing to see here
  default:
log.Fataf("Error is of type %T,n", err)
  }



On Monday, 2 October 2017 15:25:37 UTC+1, Jakob Borg wrote:
>
> Presumably OP means that the actual type of the error is not exported and 
> cant be type switched upon. 
>
> However, the syscall errors are typically syscall.Errno and can be 
> inspected for their numeric value, obviating the need to look at the 
> string. It's rather platform specific though at that point. 
>
> //jb 
>
> > On 2 Oct 2017, at 15:59, Jan Mercl <0xj...@gmail.com > 
> wrote: 
> > 
> > On Mon, Oct 2, 2017 at 2:51 PM Chris Hopkins <cbeho...@gmail.com 
> > wrote: 
> > 
> > > Yes, it has dynamic type. That doesn't mean you can't test against it. 
> > > I thought the preferred way to to handle errors was for a package to 
> expert the error variables, then you could test for those variables as in 
> the above code. 
> > 
> > The code shown uses only type switches, so it will always  work. I don't 
> know what "does not work". 
> > 
> > 
> > -- 
> > -j 
> > 
> > 
> > -- 
> > 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 . 
> > For more options, visit https://groups.google.com/d/optout. 
>
>

-- 
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.


Re: [go-nuts] Errors out of syscall

2017-10-02 Thread Chris Hopkins
So I guess another way of phrasing this question is, is this post gospel:
https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully

If so, is there a plan to backport this into the whole standard library?

Regards & Apoligies

Chris

On Monday, 2 October 2017 13:51:24 UTC+1, Chris Hopkins wrote:
>
> Yes, it has dynamic type. That doesn't mean you can't test against it.
> I thought the preferred way to to handle errors was for a package to 
> expert the error variables, then you could test for those variables as in 
> the above code.
>
> For the packages that don't do that you can call Error on the error 
> interface and get a string which you can then search through to reverse 
> engineer the error. But that's a horrid way to do it and IMO is the sign of 
> a broken package.
>
> Maybe I'm doing this all wrong, but there is very little documentation out 
> there I've found on how to actually HANDLE errors in go. Having just 
> googled it, out of the top 10 hits on "golang error handling" only 2 of the 
> hits actually talked about how to work with an error's value rather than 
> some version of "oops something has gone wrong, return the error for 
> someone else to deal with".
>
> Chris
>
> On Monday, 2 October 2017 13:35:27 UTC+1, Jan Mercl wrote:
>>
>> On Mon, Oct 2, 2017 at 2:19 PM Chris Hopkins <cbeho...@gmail.com> wrote:
>>
>> I'm not sure I understand: error is an interface and it always has some 
>> dynamic type when non-nil. But that type cannot by string b/c string does 
>> not implement the error interface.
>>
>> -- 
>>
>> -j
>>
>

-- 
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.


Re: [go-nuts] Errors out of syscall

2017-10-02 Thread Chris Hopkins
Yes, it has dynamic type. That doesn't mean you can't test against it.
I thought the preferred way to to handle errors was for a package to expert 
the error variables, then you could test for those variables as in the 
above code.

For the packages that don't do that you can call Error on the error 
interface and get a string which you can then search through to reverse 
engineer the error. But that's a horrid way to do it and IMO is the sign of 
a broken package.

Maybe I'm doing this all wrong, but there is very little documentation out 
there I've found on how to actually HANDLE errors in go. Having just 
googled it, out of the top 10 hits on "golang error handling" only 2 of the 
hits actually talked about how to work with an error's value rather than 
some version of "oops something has gone wrong, return the error for 
someone else to deal with".

Chris

On Monday, 2 October 2017 13:35:27 UTC+1, Jan Mercl wrote:
>
> On Mon, Oct 2, 2017 at 2:19 PM Chris Hopkins <cbeho...@gmail.com 
> > wrote:
>
> I'm not sure I understand: error is an interface and it always has some 
> dynamic type when non-nil. But that type cannot by string b/c string does 
> not implement the error interface.
>
> -- 
>
> -j
>

-- 
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.


[go-nuts] Errors out of syscall

2017-10-02 Thread Chris Hopkins
Hi,
I'm used to doing error handling like the following:


  out, err := os.Create(potential_file_name)
  switch t := err.(type) {
  case *os.PathError:
switch t.Err {
case os.ErrNotExist:
 etc...

However I came a cropper with an error that I traced to coming out of 
syscall - specifically:
syscall/zerrors_linux_arm.go

Where the error code back from the os is translated into just a text 
string. This makes it an annoying error to test for as it has no type, just 
a string to process. I believe this is against the intended method of go 
error handling.
Or am i missing something basic here? Is there a clever way I am missing to 
check for which of these low level errors it is without parsing a text 
string (Which feels very retro)?

Regards

Chris

-- 
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.


[go-nuts] Memory Benchmarking

2017-09-14 Thread Chris Hopkins
Hi,
I've got a reasonably performance critical piece of code that I'm trying to 
profile and I suspect is being limited by the number of memory allocations 
I am doing. I understand a good tool is:

go test -c . -gcflags='-m'

Which gives some very useful results. However I haven't found any real 
documentation on how to interpret the results and some of the output is 
puzzling me. My aim is to restructure my code so that for the critical path 
of the code, heap allocation is avoided whenever possible. Without sharing 
all the code I get a lot of things like this:

./cnt.go:420: leaking param content: prs
./cnt.go:420: leaking param content: inP

Which is in reference to the following code snippet: 
func (prs *Proofs) MergeLst(inP proofLst) {
prfLst := inP.Proofs()
for i, v := range inP.Values() {
prs.mrg(v, prfLst[i])
}
}

If I understand the message correctly the content of the variable prs is 
escaping, and therefore is at risk of being put on the heap. (Although I 
find no accompanying "escaped to Heap" message so maybe not). 
If the message means "A copy of the data contained in the structure 
referenced is being taken", then that's fine. If however it is: "Because we 
have seen that the function mrg requires a pointer receiver, prs needs to 
be allocated on the heap" then I believe that is incorrect and I need to 
restructure my code to avoid this. 
I'm pondering if the message means something else entirely, but I'm at a 
bit of a loss to be sure.

Any thoughts appreciated.

Chris

-- 
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.


Re: [go-nuts] Go channels overused and hyped?

2017-08-11 Thread Chris Hopkins
[sorry for the side question but:]
When there is the "channels are expensive" consideration, I assume that is 
from a latency perspective rather than a throughput perspective.
i.e. it was my understanding that channels had a small overhead on top of a 
basic lock, but otherwise added very little workload. The microsecond or so 
of cost you see I understood was *not* due to there being thousands of 
operations needed to run the channel, but the latency added by the stall, 
and scheduler overhead.
I also understood that in the case of an uncontested buffered partially 
full channel*, the cost of a channel was effectively that of checking the 
head and tail pointers; therefore as close to nothing as makes no 
difference.

* I know this is a rare case, but I'd also argue it's the only interesting 
one in data flow applications if you're concerned about the latency as in 
other cases you will have a contested lock and therefore the overhead of 
the locking will dominate. (I'm not wanting to worry at the moment about 
say a lock on a shared data structure (state table?) that is modified 
infrequently as I'd be surprised if this was done by channels in most 
applications)

If that makes sense?

Regards


On Friday, 11 August 2017 12:58:54 UTC+1, Jesper Louis Andersen wrote:
>
> On Tue, Aug 8, 2017 at 8:01 AM snmed  
> wrote:
>
>>
>> I stumbled over a nice and very interesting Blog entry "Go channels are 
>> bad and you should feel bad 
>> "
>>  
>> , I would like to hear some opinions about that article
>> from seasoned go developers. Because I just used go for a couple of 
>> months for my private web projects and rarely get in touch with channels.
>>
>>
> One way of putting it is that any synchronization/communication primitive 
> will have an overhead in a system. Channels are "fairly expensive" compared 
> to other methods. But if the processing you are doing is going to take 
> orders of magnitude more time than the channel communication, then you can 
> usually benefit from channels having some extra features in them, 
> especially w.r.t. system correctness: they are often easier to program with.
>
> You can create an exaggerated situation: suppose you are in the EU and you 
> decide that you want to distribute your system. You buy a server in 
> Australia. Imagine you have a mythical failure free connection to Australia 
> and you are doing RPC. You are easily looking at 300+ ms roundtrip times. 
> If the task you execute on the Australian server is "add two numbers", then 
> the 300ms overhead is a problem.
>
> But, if the task you are shipping to Australia is an NP-complete route 
> planning you want solved to optimality, you are easily looking at hours of 
> processing time. And then 300ms seems pretty quick!
>
> Channels work much the same, but the window is at the microsecond level. 
> If you protect an operation in the nanosecond scale by a channel, then the 
> channel overhead will dominate. But if you require milliseconds of 
> processing time, then a channel is fairly cheap.
>
> Note that any communication to the outside world is likely to be on the 
> millisecond scale, and that makes channels excellent as a tool to handle an 
> operation which block on some foreign input. 
>

-- 
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.


[go-nuts] Re: Why can't we do timer related works in sysmon rather than another timer goroutine?

2017-08-11 Thread Chris Hopkins
I had written a really long answer, but I suspect I may be misunderstanding 
what you are proposing. (Apologies if I misunderstand you here, but if I am 
misunderstanding you, then my long answer would have been even more 
patronising than i worry this already is.)

You have some code you wish to run each timer event. In a large system 
there may be a great many things that you want to run on some multiple 
count of this timer event.

At the moment the code you wish to run is in a go routine that (I am 
assuming) waits for a channel event to run. Therefore you have many 
routines waiting to be triggered by a number of channel events. 
Instead you believe it would be better to register a (lambda?) function you 
wish to run on each timer event so that rather than having to do a full cpu 
context swap between threads, you could instead simply jump to the code 
that needs running.

Best Regards

Chris


On Friday, 11 August 2017 06:32:33 UTC+1, Cholerae Hu wrote:
>
> Currently if we use timer or something, runtime will start a new goroutine 
> to do timerproc works. Why can't we check timer heap in each iteration of 
> sysmon if any timer exists? This may reduce some context switchs, I think.
>

-- 
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.


Re: [go-nuts] Re: GO Vs D

2017-08-02 Thread Chris Hopkins


On Wednesday, 2 August 2017 09:46:08 UTC+1, ecstati...@gmail.com wrote:
>
> And btw, this doesn't mean that just because there are genericity and 
> polymorphism in D, that I must use them.
>
> No, but the person reading your code must understand them.  Not only that 
but they must understand the "clever" way you have used them.
I came to go for the concurrency, I stayed for the fact that I have yet to 
come across a piece of code I can't quickly understand.

Every other language I come across that has "advanced" features seems to be 
an exercise in programmer vanity showing off how clever they are. I spend 
way more time & brain power trying to reverse engineer someone either 
showing off their "clever" use of an obscure part of the language than they 
could ever save with a few less keystrokes.
The trouble with gerericity and polymorphism and operator overload and all 
the others are they hide functionality which is great from an academic 
perpective; when it comes down to debugging what on earth is going wrong 
they are IME a nightmare.

I think this is why this is turning into a holy war on this list, they are 
without a doubt great ideas that in theory hide complexity and provide 
better abstraction and lots of other good things that we should all strive 
for. The trouble is, in practice many find them to be too powerful for real 
world use except in certain carefully controlled examples.

I get the impression you want them to make writing code quicker, do you not 
then share the opinion that in practice for large poorly understood 3rd 
party systems they make comprehension harder?

Regards

-- 
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.


Re: [go-nuts] Re: Go's scheduler always “stuck” after certain time when executing the code below

2017-06-21 Thread Chris Hopkins

>
>
> Particularly, delays should be implemented using the functions in the time
>
> package, not by burning CPU cycles at the expense of other useful work 
>
> that could have been done instead.
>
>  
> Sure this kinda of dead loop is just an simulation about some really CPU 
> intensive jobs.
> And I think for those kind of job, the delay about range [20 ms- inf ms) 
> is quite ordinary.
> Thus I think that kind of writing is acceptable :D
>
> It seems really pointless if you've got lots of work to do to have to sit 
in a delay.
 Would not a call to runtime.Gosched() be more efficient. That way you 
accept that you yeald to other procs, but still allow yourself to be 
rescheduled immediately if there is nothing else in the queue?

-- 
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.


[go-nuts] Re: why received can be defined with/without pointer?

2017-05-11 Thread Chris Hopkins
I think what you're saying is that it's more natural and obvious that when 
you have a function that changes something it would be more obvious and 
simple if it actually did modify the thing you gave it.
Having to jump through hoops to actually make the change you asked for 
stick is annoying.

Yes? Is that what you mean? Is this a commentary on the effect this has on 
ease of code read and writability?

What I have come to realise recently by working on ever larger projects is 
that no that's not annoying. When debugging code I don't understand often 
half the challenge is working out how a piece of data has changed that 
shouldn't have been. In the world you describe anything that touched that 
variable could be to blame for my problems. If instead you have to jump 
through hoops to make modifications and those modifications are really 
obvious where they are happening you make debugging easier.
Forcing the behaviour that "functions/methods don't modify their associated 
structures" means people structure their code differently that in my 
experience means instead of code that reads:
foo.DoUsefulStuff(i) // has foo become corrupted? changed, who knows?

you instead see code like:
fred = foo.Lookup(i) // Complex function that changes nothing in foo
foo = foo.ReturnUsefulStuff(fred) // This returns a corrupted structure

For a start you look at the function definitions and see quickly that they 
are not modifying the underlying structures so it's quick to discount a 
large chunk of code as the a source of the problem. This is not so much of 
a problem in your examples but in large undocumented projects where you 
don't understand 99% of the code the small things make it much faster to 
isolate where things could be going wrong.

Please don't take this though as anything other than a commentary on the 
code I like to read. "Code is written for humans to read and only 
incidentally for machines to execute". I believe code is read by humans way 
more times than it is written, so anything at all that isolates the code 
and makes it easier to understand is worth putting time and effort into. 

YMMV

On Thursday, 11 May 2017 11:39:18 UTC+1, mhh...@gmail.com wrote:
>
> Hi,
>
> thanks again!
>
> I m not the one to validate a perfect answer,
> i can simply tell that from my go learning and understanding,
> i agree top notch 200% no question there 
> on this description,
> which is weird in fact.
>
> I d only remark about this,
> > so there are actually just two cases: Method is on pointer receiver or 
> not. 
>
> From the declarer side, 
> there is indeed only 2 cases, 
> which accounts for 50% of the whole,
> declaration + consumption,
> the consumer is still accountable for the remaining
> 50% of the instance consumption and usage.
>
> Does it make it less dead simple ?
>
> In my example i might have named the method as `whatever`,
> still there is an explicit value set on a receiver property.
> I don t feel like i have assumed anything from the method name.
>
>
> On Thursday, May 11, 2017 at 12:17:00 PM UTC+2, Volker Dobler wrote:
>>
>> On Thursday, 11 May 2017 11:28:33 UTC+2, mhh...@gmail.com wrote:
>>>
>>> //defined
 var x {} // put on heap
 var x T // put on stack

 This is definitely a misconception: Allocation on heap vs stack is
 totaly unrelated to value methods vs pointer methods. Both examples
 might be allocated on the stack or on the heap and this depends
 on other factors than methods of T.

>>>
>>> what are other factors ? 
>>>
>>
>> Roughly: If the compiler cannot prove that x *can* be safely put on the
>> stack then it must go to the heap. Values cannot go safely to the stack
>> if they might outlive the scope of this stack frame / the current 
>> function.
>> This can happen if e.g. a pointer to such value leaves the function, e.g.
>> in a return or a channel send. Search for escape analysis if you are 
>> interested in the gory details, but I'd urge you not to until the basic 
>> stuff
>> is total clear.
>>  
>>
>>> (let s keep it short, optimized code is not a topic for me)
>>> I understood that the next func call (might be method) 
>>> will decide how the instance (to not say value here) is passed.
>>>
>>> is it ?
>>>
>>
>> Each and every function --- be it a normal function, a function literal,
>> a closure, a method, whatever --- completely determines its arguments.
>> This includes the receiver of a method which technical is just a normal
>> (the first) function argument.
>> A func f(int) is called with an argument of type int and a func g(*int) is
>> called with a *int. The same is true for receivers. There is *no* magic 
>> here! 
>>
>> The only thing "magical" with methods and their special receiver
>> argument that the compiler automatically (automagically) takes the
>> address of a value or dereferences a pointer to match the method
>> signature. That's all. That's convenience only. A bit less typing, a bit
>> fewer braces, it reads nicer.
>>
>> So: 

[go-nuts] Re: why received can be defined with/without pointer?

2017-05-11 Thread Chris Hopkins

>
>
>
> In this code,
> starting at 0,
> is case 1 not an aberration,
> is case 3 is useless
> https://play.golang.org/p/VyOfZyt7rw
>
> Note case 0 is expected to fail and might be detected.
>
>>
>> As a dumb hardware engineer I too have struggled with this in the past.
2 rules I find helped:
1) Everything into a function is passed as a copy
2) If you need to modify something passed to you in a function then you 
need not a copy of the thing but the address of the thing you want to modify
so taking your code for both cases 0 & 1:
 func (v valueType) SetName(n string) {
v.Name = n
}
when this function runs a local bit of storage is created (probably on the 
stack as escape analysis would determine that the value can't escape the 
scope) and the current value of the data is copied into that storage. That 
storage is then modified. The function then returns. The local storage goes 
out of scope and you are left with your original data unchanged.

for cases 2&3
func (v *refType) SetName(n string) {
v.Name = n
}
This time again the function runs and there is a local piece of storage 
created (again called v) this time the local storage (probably on the stack 
as v cannot escape the scope of that function) and v gets the pointer to 
the variable it was called on copied into it instead of the value.
So when you set the name it uses the local copy of the pointer to access 
the Name field. Because this is pointing to the underlying storage for the 
original structure that structure is modified. 
What might be causing confusion here (because it used to confuse me with 
go) is that go is doing something automatically under the hood. When you 
type v.Name it knows that *refType does not have a field Name. It knows 
that you're trying to access the structure addressed by the pointer and so 
automatically de-references the pointer for you i.e. takes the address held 
in v, works out what offset from that address it has to use to get at the 
Name field and then directs the assignment to that new address.

At least that's how I think it works. I'm sure someone will correct me, as 
this would otherwise be the first time I had this low level detail of 
software correct ;-)

HTH

Chris

-- 
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.


[go-nuts] Unreliable Network Testing

2017-05-04 Thread Chris Hopkins
Hi,
Before I re-invent the wheel:
We've (all) used net.Pipe to model a network connection in testbenches. For 
my purposes it would be handy if I had one that was more realistic. i.e. it 
dropped some packets and re-ordered some, maybe even duplicated a few, 
added (random) delays to sending etc.
Now it doesn't have to be realistic from a benchmarking perspective, it 
would just be good to make sure my application can cope with the sort of 
nonsense a real application does.

Does such a thing already exist?

I mocked up a rough attempt at one based on net.Pipe, but the issue seemed 
to be that I had visibility of io.Writer/Reader calls. This meant that I 
couldn't guarantee that one call to the UnreliablePipe corresponded to one 
packet. In fact what seemed to be happening was that I often got a fragment 
of a packet as the Writer broke up the packet into multiple calls(This 
might be an artefact of how I was structuring the buffers, needs debugging).
As I say before I go too far down this particular rabbit hole I thought I 
should ask if anyone is aware of solving this problem already.

Any thoughts?

Many Thanks

Chris

-- 
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.


Re: [go-nuts] Errors from Gob

2017-05-03 Thread Chris Hopkins
Yeah until the comment about NFS I hadn't thought that the file system
would be generating those errors and passing that through to Gob back to
me. Silly in retrospect, sorry.

I wasn't aware of that architecture that there was a mapping within Go from
the error number to an error string.

Could I check with the community what the best practice on this should be?
Should I be searching through error strings for expected error messages, or
should there be another method?
My understanding was that best practice for packages was to declare each
error as its own constant that could then be checked for. e.g. like io has
an EOF constant, I assumed that best practice was that packages should
declare and export those.
This would imply that the syscall package should be modified to export each
of these error types as constants that can be checked for?

FWIW I think there may be an error message mis-map as breaking the calls
into 1k size has removed the error. When I get the chance I'll try and
investigate more, but the depths of syscalls is outside my comfort zone.

Thanks

Chris


On 30 April 2017 at 01:41, Lars Seipel <lars.sei...@gmail.com> wrote:

> On Thu, Apr 27, 2017 at 08:55:36AM -0700, Chris Hopkins wrote:
> > What's the current thinking on this sort of error handling? It's hard to
> > say "Handle errors properly" when the standard library is butchering the
> > original error message.
>
> This most likely *is* the original error, as returned by your system.
> It corresponds to the EHOSTDOWN error code and was apparently
> encountered during a write system call.
>
> The system call interface on Unix just doesn't give you any more than
> this. You need to look up the conditions under which your system might
> return that particular error code.
>
> If you really think the message is bogus, you might want to compare the
> errno-to-errstr mapping in package syscall against your local system
> headers. This is going to depend on OS and arch, of course.
>

-- 
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.


[go-nuts] Errors from Gob

2017-04-27 Thread Chris Hopkins
So amusingly I've just had Gob report the following error:

panic: write gob_fetch.txt: host is down

It referring to a file as a host is of course understandable but it's a 
little troublesome because as far as I can tell the file should be 
perfectly writable having just been created and checked for errors on 
os.Create a few lines earlier.
I have a vague memory that there was a package someone major in the Go 
project wrote to create an error stack. I guess this hasn't been ported to 
the whole standard library given the above error.

What's the current thinking on this sort of error handling? It's hard to 
say "Handle errors properly" when the standard library is butchering the 
original error message. Or is there a way to extract the source error 
message that I am missing? [at the moment I'm just doing a panic(err)]

Thanks

Chris

-- 
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.


[go-nuts] Re: bytes.Buffer WriteAt

2017-04-26 Thread Chris Hopkins
Apologies for replying to myself.
Digging into the source it looks like I had misunderstood the 
purpose/functionality of bytes.Buffer.
Sorry. Please ignore/delete the question.

On Wednesday, 26 April 2017 10:21:10 UTC+1, Chris Hopkins wrote:
>
> Hi,
> Random question:
> I'm just starting implementing a file cache and using a bytes.Buffer in my 
> testbench as a model of a perfect file.
> One slight imperfection, the standard bytes.Buffer does not implement 
> WriteAt which I find a little odd as it does implement ReadAt.
> Now this is easy enough to work around, but I wondered if anyone knew the 
> thinking behind it? Is it just no-one has bothered implementing it yet (I 
> find this surprising) or am I missing something subtle here? If no-one has 
> bothered implementing it, should I be publishing my workaround for future 
> inclusion?
>
> Background:
> All the caches I've found so far seem based around http. Whereas I'm 
> dealing with a large (pair of) file(s) that I expect to be accessing a 
> small portion of, so a per file cache that caches read and write accesses 
> seems like a really obvious thing to use. However I cannot find anyone else 
> having written something similar. I guess people are just relying on the 
> file system to do this for them.
>
> Thanks
>
> Chris
>
>
>

-- 
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.


Re: [go-nuts] Zero value of the map

2017-04-18 Thread Chris Hopkins
I'm not sure what you mean by the append doesn't modify the original. 
Append will use the same backing store (if there is available capacity in 
it) and by definition the address of the slice in question must be 
invariant across its context. e.g.: https://play.golang.org/p/lBRpKSo-9P
I think of a slice as a built in structure so the pointer to the backing 
store will stay the same, the capacity will stay the same, only the length 
will change with append. (unless there is insufficient capacity then all 
bets are off except that again the original structure will remain, but all 
the values in it will be overwritten, then copied back into the original 
struct)

Or have I really misunderstood what happens under the hood here?

On Tuesday, 18 April 2017 13:09:11 UTC+1, Ian Davis wrote:
>
>
> On Tue, 18 Apr 2017, at 01:04 PM, Tad Vizbaras wrote:
>
>
> The argument could be that slices are read-only too. Just that "append" is 
> special and it makes zero value slices useful.
> var a []int
> a[0] = 1 // Fails.
> // panic: runtime error: index out of range
>
> I am just curious what is the reason behind not making zero maps more 
> useful? Is it space?
>
>
> A nitpick: slices are always read only. append creates a new slice, it 
> doesn't modify the original.
>
> In that respect map and slice zero value behaviours are similar.
>
> Ian
>

-- 
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.