[go-nuts] Re: How to lowercase all field names for MarshalJSON and UnmarshalJSON?

2018-03-05 Thread Alex Buchanan
Thanks, that does look helpful, although I'll need to evaluate the 
tradeoffs of not using the std lib. It's hard to believe a library could be 
substantially faster than the stdlib without giving something up.


On Monday, March 5, 2018 at 9:52:04 PM UTC-8, Tamás Gulácsi wrote:
>
> You can try github.com/json-iterator/go, it allows several naming 
> strategies (
> https://github.com/json-iterator/go/blob/master/extra/naming_strategy.go#L9), 
> even custom ones.

-- 
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: confusing differences in reflect Type knowledge for a receiver vs. an argument

2018-03-05 Thread Randall O'Reilly
On Mar 5, 2018, at 10:32 PM, Ian Lance Taylor  wrote:
> 
> Go doesn't have anything like inheritance in C++.  What you are
> calling the "true underlying type" simply doesn't exist in Go.  Go has
> embedded fields, and methods of embedded fields are promoted to become
> methods of the outer type in which they are embedded.  But the outer
> type does not inherit anything from the inner type, at least not if
> you are using the word "inherit" in the sense that it is used in C++.
> The promoted methods are still methods on the inner type, they are
> just accessible directly from the outer type.
> 
> I think it's generally best to approach these problems in terms of how
> Go works, rather than trying to recreate C++ approaches in Go.  Go
> doesn't work the way that C++ does.
> 
> Ian

So why then does reflect.TypeOf(obj) return the “Outer” type in the example 
code I posted, here:

func ArgFun(in InType) {
typ := reflect.TypeOf(in).Elem()
fmt.Printf("ArgFun on in tells the truth: %v\n", typ.Name())
}

https://play.golang.org/p/KmihXxU19Dd

I don’t think json.Marshal etc would work without this behavior..

Per the discussion here: https://github.com/golang/go/issues/22013 — it seems 
like Go is rather unclear about exactly what level of C++-like inheritance it 
wants to support.  I don’t want to recreate any of that discussion here, but 
I’ll just add a tiny vote for at least keeping the notion of embedding as it is 
— don’t throw the baby out with the bathwater!  The presence of interfaces and 
the compositional model in Go is TONS better than C++’s rigid inheritance 
constraints, but sometimes a simple inherit-and-extend model is just the right 
thing, and it seems like it doesn’t add that much additional complexity to 
support it.  Maybe just need to add a bit of relevant docs in places to resolve 
residual confusions, such as the one I encountered.  Thanks for all your hard 
work on creating this awesome language!

- Randy



-- 
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: How to lowercase all field names for MarshalJSON and UnmarshalJSON?

2018-03-05 Thread Tamás Gulácsi
You can try github.com/json-iterator/go, it allows several naming strategies 
(https://github.com/json-iterator/go/blob/master/extra/naming_strategy.go#L9), 
even custom ones.

-- 
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: confusing differences in reflect Type knowledge for a receiver vs. an argument

2018-03-05 Thread Ian Lance Taylor
On Mon, Mar 5, 2018 at 8:08 PM, Randall O'Reilly  wrote:
> Thank you for that clarification of what is happening under the hood.
>
> Nevertheless, I do think there are many cases where it would be very valuable 
> to have access through reflect of the true underlying type of the receiver 
> struct.  This is evident in that stack overflow question, the *JSON code, and 
> probably many other cases where reflect is used.  Just to be clear, in the 
> [Un]MarshalJSON code, the inability to access the true type means that you 
> cannot use an embedded interface to properly serialize derived types — any 
> generic functionality you might want to add to the process must be added 
> explicitly to each instance separately.  This leads to a need for major code 
> replication, seemingly in contradiction to the Go philosophy.  Furthermore, I 
> have many use-cases of wanting to generically access fields (Get / Set 
> values, etc) that might be on a derived type of my tree Node type.
>
> Anyway, if it is not technically possible, then there’s no point in wishing 
> for it.  But I don’t think it is accurate to say that this would not extend 
> the power and elegance of the language.
>
> Meanwhile, in case others encounter this same situation, I have had to add a 
> “this” member to my Node struct that stores the interface pointer version of 
> the struct, so it is always possible to use that when access to the derived 
> type is necessary.  Might make some Go folks barf, but it does the trick!  
> Just trying to get stuff working with the fewest LOC possible :)

Go doesn't have anything like inheritance in C++.  What you are
calling the "true underlying type" simply doesn't exist in Go.  Go has
embedded fields, and methods of embedded fields are promoted to become
methods of the outer type in which they are embedded.  But the outer
type does not inherit anything from the inner type, at least not if
you are using the word "inherit" in the sense that it is used in C++.
The promoted methods are still methods on the inner type, they are
just accessible directly from the outer type.

I think it's generally best to approach these problems in terms of how
Go works, rather than trying to recreate C++ approaches in Go.  Go
doesn't work the way that C++ does.

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: Go Games

2018-03-05 Thread Fino
on client side,  most of the developer team will use Unity or Unreal engine 
to save time, 

so it working this way, choose the commercial tool are more 
critical than choose language itself, 

BR fino 

-- 
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: How to lowercase all field names for MarshalJSON and UnmarshalJSON?

2018-03-05 Thread Alex Buchanan
I'm bummed there still isn't a good solution for this. It seems like such 
an easy and extremely common thing. In a decade of webdev, I've possibly 
never seen a JSON API with Golang style UpperCamelCase keys.

Is there a solution to this that I'm missing? 

Here's one project I'm working on where dozens of types need to have 
JSON/YAML formats: https://godoc.org/github.com/buchanae/cwl

Every single struct field needs a really obvious duplication of the field 
name in the tags, just in camel case. There are 3-4 variable name styles 
that would cover a majority of the data out there: camelCase, snake_case, 
etc. (Maybe I should do a code crawling exercise and get some numbers on 
how often tags are an obvious conversion of the field name...)

My documentation and code would rejoice if encoding/json added a callback 
for formatting the key name.

Can we just add a call to a callback 
here? https://golang.org/src/encoding/json/encode.go#L1110





On Monday, July 7, 2014 at 12:22:08 AM UTC-7, Dave Cheney wrote:
>
>
>
> On Saturday, 5 July 2014 18:36:06 UTC+10, i...@bodokaiser.io wrote:
>>
>> Hello,
>>
>> I would like to have all field names of a struct lower cased by default. 
>> At the moment I define the lowercased field name as json tag:
>>
>> type FooBar struct {
>> Id string `json:"id"`
>> }
>>
>> However with bson-, validation-, database- and xml-tags the space is 
>> getting very very tight.
>>
>
> Why is space tight ? Do you need to use a smaller font ?
>
> Seriously for moment, tags are the _correct_ solution for this. Apart from 
> a potential aesthetic issue, is there a specific reason why you don't want 
> to use them ?
>  
>
>>
>> Is there some hack how to implement the Unmarshaler Interface with just 
>> lowercasing all field names before proceeding?
>>
>> Bo
>>
>

-- 
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: confusing differences in reflect Type knowledge for a receiver vs. an argument

2018-03-05 Thread Randall O'Reilly
Thank you for that clarification of what is happening under the hood.

Nevertheless, I do think there are many cases where it would be very valuable 
to have access through reflect of the true underlying type of the receiver 
struct.  This is evident in that stack overflow question, the *JSON code, and 
probably many other cases where reflect is used.  Just to be clear, in the 
[Un]MarshalJSON code, the inability to access the true type means that you 
cannot use an embedded interface to properly serialize derived types — any 
generic functionality you might want to add to the process must be added 
explicitly to each instance separately.  This leads to a need for major code 
replication, seemingly in contradiction to the Go philosophy.  Furthermore, I 
have many use-cases of wanting to generically access fields (Get / Set values, 
etc) that might be on a derived type of my tree Node type.

Anyway, if it is not technically possible, then there’s no point in wishing for 
it.  But I don’t think it is accurate to say that this would not extend the 
power and elegance of the language.

Meanwhile, in case others encounter this same situation, I have had to add a 
“this” member to my Node struct that stores the interface pointer version of 
the struct, so it is always possible to use that when access to the derived 
type is necessary.  Might make some Go folks barf, but it does the trick!  Just 
trying to get stuff working with the fewest LOC possible :)

- Randy

> On Mar 5, 2018, at 2:24 PM, Krzysztof Kowalczyk  wrote:
> 
> (in *Inner) InFunc() can't possibly say `in` is Outer.
> 
> This piece of code:
> 
> var := Outer{}
> val.InFunc()
> 
> Is really:
> 
> val := Outer{}
> var tmpInner *Inner = &(val.Inner)
> tmpInner.InFunc()
> 
> What is passed to InFunc is a pointer to Inner struct embedded inside Outer 
> struct, not a pointer to Outer struct.
> 
> The compiler did a little bit of magic behind the scenes because it makes 
> using struct composition more convenient.
> 
> The idea is that if you include Inner struct inside Outer struct, Outer 
> "inherits" fields and functions of Inner so syntactically you can say 
> outer.Foo() and it will call function defined in Inner() without you having 
> to say outer.Inner.Foo().
> 
> There's also confusion about what reflection is for.
> 
> In (in *Inner) InFoo() you already know the static type of in, which is a 
> pointer to struct Inner. There's no need to use reflection.
> 
> Reflection is for cases where you have interface type, including the most 
> common case of empty interface `interface{}`.
> 
> You can convert any value with static type to `interface{}`
> 
> var inter interface{} = in // you can convert any static type to interface{}
> // code using reflection on inter
> 
> // it := in.(InType) // the "obvious" thing fails with: invalid type 
> assertion: in.(InType) (non-interface type *Inner on left)
> 
> Here you can't use type assertion on `in` because it only works on interfaces 
> (https://www.programming-books.io/essential/go/a-25362-type-assertion) and 
> `in` isn't an interface. The compiler tells you so.
> 
> -- kjk
> 
> On Monday, March 5, 2018 at 10:28:25 AM UTC-8, Randall O'Reilly wrote:
> I'm new to golang, and am hitting some seemingly strange territory that I 
> couldn't find much prior discussion about -- here's one example of the 
> phenomenon in question:
> 
> https://stackoverflow.com/questions/22153269/how-to-reflect-fields-of-containing-struct-from-a-method-of-the-embedded-struct/49094937#49094937
> 
> In brief, it seems that reflect does NOT have access to the "true" underlying 
> type of a struct, when accessing a function receiver struct pointer, but it 
> DOES have access when an object is passed as a regular argument via an 
> interface.  While I understand that the receiver is apparently special in 
> terms of binding to the interface, there is also the statement that it is 
> really just another arg..
> 
> In my use-case, I was trying to use reflect to provide some generic tree 
> functionality that could automatically apply to "derived" types that embed a 
> "Node" type with all the tree-relevant functionality.  However, depending on 
> this difference in where the struct appeared (receiver vs. arg) I was 
> variably getting the desired "inheritance" ability to access the fields of 
> the derived types in the base type's code.  In particular, defining a 
> MarshalJSON method for my base type forced everything to be Marshal'd as the 
> base type, not as its actual type -- the generic Marshal gets the struct as 
> an arg, whereas when you define this method you turn it into a receiver!
> 
> This issue generally seems relevant to this discussion about the value of 
> struct embedding and the true nature of inheritance in Go: 
> https://github.com/golang/go/issues/22013 -- as someone coming from the C++ 
> world, I find the ability to get at least some basic inheritance 
> functionality to be very powerful, 

[go-nuts] Re: Gift wrap errors or not?

2018-03-05 Thread adam.azarchs via golang-nuts
Errors in Go aren't really used the same was as exceptions in other 
languages, and that's a good thing!  Most of the time, all you care about 
is whether the error is non-nil or not.  Occasionally you care about the 
specific type of error, in which case the package emitting the error should 
define a test method or constant to compare to (as with io.IsNotExit()).  
Beyond that, erros are just things you throw into your debug log.  If it's 
useful to you to include stack information in the error message, you can do 
so.  fmt.Errorf() is my usual method of formatting errors for such things.

I hesitate to mention this, since it leads to a lot of bad practice in my 
opinion, but if you want something that acts more like other languages' 
versions of exceptions, you can always use panic/recover...

On Thursday, March 1, 2018 at 12:19:16 PM UTC-8, Tad Vizbaras wrote:
>
> It has been almost two years since this post:
> https://dave.cheney.net/2016/06/12/stack-traces-and-the-errors-package
>
> What is current best practice? Should I use some package to gift wrap 
> errors in order to get stack trace attached to them?
>
> Standard library errors package is really "bare bones". Some guidance 
> would be appreciated.
>

-- 
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] Memory copy on return statement (copy elision)

2018-03-05 Thread Bruno Novais
Andrey,

Thank you for your help!! I've been analysing the output of my code, and it
seems that me and the compiler are "thinking" the same way.

I saw this options when I started learning Go, but I didn't realize it
could help me like that.
I will read more about escape analysis, thanks for pointing out the correct
search term.

Best Regards,
Bruno Novais

2018-03-04 18:37 GMT-03:00 andrey mirtchovski :

> Use 'go build -gcflags="-m"' to see what inlining actions the compiler
> takes. more here:
> https://github.com/golang/go/wiki/CompilerOptimizations#
> escape-analysis-and-inlining
>
> for example this https://play.golang.org/p/QyAauePKbn- will result in:
>
> $ go build -gcflags='-m' t.go
> # command-line-arguments
> ./t.go:9:6: can inline NewStuff
> ./t.go:14:28: inlining call to NewStuff
> ./t.go:14:28: NewStuff() escapes to heap
> ./t.go:14:12: main ... argument does not escape
> $
>
>
> multiple -m options may be supplied, although the extra output isn't
> especially user-friendly :)
>
> On Sun, Mar 4, 2018 at 6:57 AM, Bruno Novais 
> wrote:
> > Hello Gophers!
> >
> > As you probably noticed by my question, I'm new to this awesome language
> > called Go (coming from C/C++). In C++ I rely a lot on constructor (copy)
> > elision. I think Go doesn't have this concept, but I would like to know
> what
> > happen when I do something like this:
> >
> > func NewStuff() Stuff {
> >   return Sutff{}
> > }
> >
> > What will happen in that case? Will it be store on the stack, and then
> > copied to the caller function? That will probably be inlined, so:
> >
> > func NewStuff() Stuff {
> >   // A lot of pre-processing that won't be inlined.
> >
> >   return Sutff{
> > Value: var1,
> > Another: var2,
> > Etc: var3,
> >   }
> > }
> >
> > The returned value will be copied, or the compiler will optimize and
> change
> > the memory space of the caller function?
> >
> > Thank you!
> >
> > --
> > 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.
>

-- 
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] Memory copy on return statement (copy elision)

2018-03-05 Thread Bruno Novais
Ian,

good to know that in general you believe that the returned struct will be
allocated in the caller.
I do think that too, so it's good to know that I'm not thinking too much
outside the box.

Anyway, out of curiosity I will read more about the flavors of compilers
avaliable to use with Go.
To be honest, I thought there was only one compiler avaliable out there for
Go.

Thank you for your time!

Best Regards,
Bruno Novais

2018-03-05 3:25 GMT-03:00 Ian Lance Taylor :

> On Sun, Mar 4, 2018 at 5:57 AM, Bruno Novais 
> wrote:
> >
> > As you probably noticed by my question, I'm new to this awesome language
> > called Go (coming from C/C++). In C++ I rely a lot on constructor (copy)
> > elision. I think Go doesn't have this concept, but I would like to know
> what
> > happen when I do something like this:
> >
> > func NewStuff() Stuff {
> >   return Sutff{}
> > }
> >
> > What will happen in that case? Will it be store on the stack, and then
> > copied to the caller function? That will probably be inlined, so:
> >
> > func NewStuff() Stuff {
> >   // A lot of pre-processing that won't be inlined.
> >
> >   return Sutff{
> > Value: var1,
> > Another: var2,
> > Etc: var3,
> >   }
> > }
> >
> > The returned value will be copied, or the compiler will optimize and
> change
> > the memory space of the caller function?
>
> Go doesn't provide any special guarantees about this case.  Different
> implementations can do different things.
>
> That said, in general I believe that a returned struct will be
> allocated in the caller and changed directly from the callee.
>
> 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.


Re: [go-nuts] How to get an alias in a type alias ???

2018-03-05 Thread He Liu
Thank you, I understand

在 2018年3月6日星期二 UTC+8上午2:51:39,Ian Lance Taylor写道:
>
> On Mon, Mar 5, 2018 at 1:35 AM, He Liu  > wrote: 
> > 
> > package main 
> > 
> > 
> > import ( 
> > 
> > "log" 
> > 
> > "reflect" 
> > 
> > ) 
> > 
> > 
> > type AAA = int 
> > 
> > 
> > func main() { 
> > 
> > var a AAA = 5 
> > 
> > x := reflect.TypeOf(a) 
> > 
> > log.Println(x.Name()) 
> > 
> > // print int 
> > 
> > } 
> > 
> > 
> > How to get AAA ??? 
>
> You can't.  A type alias is just another name for a type.  It doesn't 
> replace the type's real name.  Type aliases only appear at compile 
> time, not at run time.  If you need the name of a type at run time, 
> you have to use a real type definition, not a type alias. 
>
> 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.


Re: [go-nuts] My views on Go and why it's better than Scripting

2018-03-05 Thread dorival . pedroso
Awesome!

I'll read the paper too.

Thanks!



On Monday, March 5, 2018 at 5:31:06 PM UTC-8, kortschak wrote:
>
> This was essentially my thinking in choosing Go to write my 
> bioinformatics library in - mainly because much of our code will be 
> written and maintained by students, but we want good performance as 
> well. 
>
> Some of my thought about this are in this paper https://www.biorxiv.org 
> /content/early/2014/05/12/005033 
>
> Dan 
>
> On Fri, 2018-03-02 at 12:07 -0800, dorival...@gmail.com  
> wrote: 
> > Hi, I could be wrong (please correct me ;-), but here you are what I 
> > think  
> > about Go: 
> > 
> > INTRODUCTION 
> > Computers and software were initially developed for scientific 
> > computing;  
> > e.g., ALGOL and FORTRAN from the 1950s! Therefore, several computer  
> > languages and libraries have been invented and are used in 
> > scientific  
> > computing to date.  Nonetheless, when programming a new scientific  
> > simulation, the question about computational efficiency versus ease- 
> > of-use  
> > remains open. Here, we aim to shed light on a suitable answer to 
> > this  
> > question---TL;DR use Go and Gosl! 
> > 
> > One would say that scripting (interpreted) languages might provide 
> > the  
> > convenient platform for computations as long as care is taken to 
> > send  
> > intensive tasks to functions pre-compiled with high-performance 
> > languages.  
> > This strategy fails to create an easy-to-use environment because the  
> > programmer needs to think when and where those tasks should go. 
> > Considering  
> > that this kind of decision is essential for performance, we argue 
> > that  
> > scripting language is not the best solution.  Furthermore, we argue 
> > that  
> > scripting is the worst tool for teaching new programmers in 
> > scientific  
> > computing. 
> > 
> > We argue that only experts should use scripting languages (scripts) 
> > for  
> > computer programming because beginners cannot understand how 
> > dangerous the  
> > flexibility of scripts can be. For example, the assignment of 
> > variables  
> > with the same name to different types is often a cause of 
> > misunderstandings  
> > and failures. To make this problem even worse, failures due to wrong 
> > types  
> > are not captured at runtime---certainly not at compilation time 
> > (there is  
> > no compilation time in scripts). In other words, the interpreter is 
> > too  
> > permissive.  The scientist, if aware (rarely the case with students), 
> > will  
> > investigate the numerical output and, after much work, will find the 
> > source  
> > of the error. Therefore, this situation is not ideal. To exemplify, 
> > the  
> > following is allowed in Python (or Julia---similar syntax): 
> > 
> > ``` 
> > a = 1.0 
> > a = "a" # OK in Python or Julia 
> > ``` 
> > 
> > In the following code, Go will detect the error with a message such 
> > as  
> > `./test.go:5: cannot use "a" (type string) as type float64 in 
> > assignment`: 
> > 
> > ``` 
> > package main 
> > func main() { 
> > a := 1.0 
> > a = "a" // not accepted in Go 
> > } 
> > ``` 
> > 
> > The problem propagates in scripting languages when developing  
> > objected-oriented code. For example, a member data of a class can be  
> > entirely modified by `anyone`, `anywhere` in Python! This issue 
> > completely  
> > defeats the purpose of encapsulation in OOP. 
> > 
> > In summary, scripting (e.g., Python) and alike (e.g., Julia, Matlab)  
> > languages are excellent for the expert programmer only who can 
> > understand  
> > what is going on. However, they are very misleading to the beginner. 
> > In  
> > other words, the strictness of compiled languages DOES help to learn  
> > computer programming. Furthermore, the tools for working with 
> > compiled  
> > language often take advantage of well-defined types. The shift 
> > towards type  
> > declaration is so apparent that new languages and strategies are 
> > being  
> > invented to overcome these issues. For example, TypeScript and 
> > Javascript  
> > (ES6) combined with FlowType have been recently developed and have a 
> > fast  
> > adoption among web developers. It seems that no new large project 
> > will use  
> > non-typed Javascript code. 
> > 
> > GO LANGUAGE 
> > Go is a modern programming language created by Google engineers in 
> > 2007,  
> > including Robert Griesemer, Rob Pike, and Ken Thompson. The language 
> > was  
> > later made public as open source in 2009. Go has since grown 
> > exponentially  
> > attracting a large number of co-developers and users. The primary 
> > goal  
> > leading to the introduction of yet a new language was the combination 
> > of  
> > efficiency (like C/C++) with ease of development (like Python). There 
> > are  
> > other several innovations and advantages in Go when compared with  
> > mainstream languages such as C/C++/C#/Java/Python/Ruby/Lua.  
> > Also, Go automatically detects Fortran and C files 

Re: [go-nuts] My views on Go and why it's better than Scripting

2018-03-05 Thread Dan Kortschak
This was essentially my thinking in choosing Go to write my
bioinformatics library in - mainly because much of our code will be
written and maintained by students, but we want good performance as
well.

Some of my thought about this are in this paper https://www.biorxiv.org
/content/early/2014/05/12/005033

Dan

On Fri, 2018-03-02 at 12:07 -0800, dorival.pedr...@gmail.com wrote:
> Hi, I could be wrong (please correct me ;-), but here you are what I
> think 
> about Go:
> 
> INTRODUCTION
> Computers and software were initially developed for scientific
> computing; 
> e.g., ALGOL and FORTRAN from the 1950s! Therefore, several computer 
> languages and libraries have been invented and are used in
> scientific 
> computing to date.  Nonetheless, when programming a new scientific 
> simulation, the question about computational efficiency versus ease-
> of-use 
> remains open. Here, we aim to shed light on a suitable answer to
> this 
> question---TL;DR use Go and Gosl!
> 
> One would say that scripting (interpreted) languages might provide
> the 
> convenient platform for computations as long as care is taken to
> send 
> intensive tasks to functions pre-compiled with high-performance
> languages. 
> This strategy fails to create an easy-to-use environment because the 
> programmer needs to think when and where those tasks should go.
> Considering 
> that this kind of decision is essential for performance, we argue
> that 
> scripting language is not the best solution.  Furthermore, we argue
> that 
> scripting is the worst tool for teaching new programmers in
> scientific 
> computing.
> 
> We argue that only experts should use scripting languages (scripts)
> for 
> computer programming because beginners cannot understand how
> dangerous the 
> flexibility of scripts can be. For example, the assignment of
> variables 
> with the same name to different types is often a cause of
> misunderstandings 
> and failures. To make this problem even worse, failures due to wrong
> types 
> are not captured at runtime---certainly not at compilation time
> (there is 
> no compilation time in scripts). In other words, the interpreter is
> too 
> permissive.  The scientist, if aware (rarely the case with students),
> will 
> investigate the numerical output and, after much work, will find the
> source 
> of the error. Therefore, this situation is not ideal. To exemplify,
> the 
> following is allowed in Python (or Julia---similar syntax):
> 
> ```
> a = 1.0
> a = "a" # OK in Python or Julia
> ```
> 
> In the following code, Go will detect the error with a message such
> as 
> `./test.go:5: cannot use "a" (type string) as type float64 in
> assignment`:
> 
> ```
> package main
> func main() {
> a := 1.0
> a = "a" // not accepted in Go
> }
> ```
> 
> The problem propagates in scripting languages when developing 
> objected-oriented code. For example, a member data of a class can be 
> entirely modified by `anyone`, `anywhere` in Python! This issue
> completely 
> defeats the purpose of encapsulation in OOP.
> 
> In summary, scripting (e.g., Python) and alike (e.g., Julia, Matlab) 
> languages are excellent for the expert programmer only who can
> understand 
> what is going on. However, they are very misleading to the beginner.
> In 
> other words, the strictness of compiled languages DOES help to learn 
> computer programming. Furthermore, the tools for working with
> compiled 
> language often take advantage of well-defined types. The shift
> towards type 
> declaration is so apparent that new languages and strategies are
> being 
> invented to overcome these issues. For example, TypeScript and
> Javascript 
> (ES6) combined with FlowType have been recently developed and have a
> fast 
> adoption among web developers. It seems that no new large project
> will use 
> non-typed Javascript code.
> 
> GO LANGUAGE
> Go is a modern programming language created by Google engineers in
> 2007, 
> including Robert Griesemer, Rob Pike, and Ken Thompson. The language
> was 
> later made public as open source in 2009. Go has since grown
> exponentially 
> attracting a large number of co-developers and users. The primary
> goal 
> leading to the introduction of yet a new language was the combination
> of 
> efficiency (like C/C++) with ease of development (like Python). There
> are 
> other several innovations and advantages in Go when compared with 
> mainstream languages such as C/C++/C#/Java/Python/Ruby/Lua. 
> Also, Go automatically detects Fortran and C files which helps
> taking 
> advantage of good existing code.
> 
> The vocabulary in Go is quite small compared to other languages,
> making 
> easy to have an overview of the syntax and available commands. Go
> avoids 
> complexities such as generics (aka templates) usually available in
> other 
> languages (e.g., C++). Go also tries to avoid unnecessary complexity
> by not 
> taking `in the language` advanced OOP concepts such as polymorphism, 
> multiple inheritances, and 

[go-nuts] Re: best practices of client middleware

2018-03-05 Thread Bojan Delić
As far as I am aware, there is very little information about best practices 
regarding client side middlewares. 

I though that having such support is neat idea and I have implemented 
something (that I use for some time now, though still in beta) that you 
might find useful for your use case. I have written small library that 
describes client middleware protocol , 
some useful middlewares  and 
HTTP 
client  that's using these libraries. 

This might solve your problem directly (writing new middleware is trivial), 
but it might introduce dependency that you don't want, so I hope this will 
provide inspiration on how you would do something similar yourself. 

On Monday, March 5, 2018 at 3:03:14 PM UTC+1, Eyal Posener wrote:
>
> Hi
>
> I want to implement a client middleware - for example: sign the request 
> body and add the signature as an HTTP header.
> I thought that the best way to do it is to implement a RoundTripper 
> interface  which up on 
> request, calculate the signature, adds the header, and invoke a "next" 
> ToundTripper.
>
> This could be a very generic implementation, which i can inject to any 
> client that uses the standard library http.Client.
>
> However, I found the following in the doc:
>
> // RoundTrip should not modify the request, except for
> // consuming and closing the Request's Body. RoundTrip may
> // read fields of the request in a separate goroutine. Callers
> // should not mutate the request until the Response's Body has
> // been closed.
>
>
> Is there a standard way to do it?
>
> Thanks,
> Eyal
>

-- 
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 gc compiler treat slice and custom type differently in garbage collection?

2018-03-05 Thread 'Keith Randall' via golang-nuts
This ideally shouldn't happen.

For some reason the compiler is keeping t.y alive across the printMemStat 
calls, even when it only needs to keep t.x alive.
I've opened an issue https://github.com/golang/go/issues/24263

On Monday, March 5, 2018 at 8:08:59 AM UTC-8, di...@veryhaha.com wrote:
>
>
>
> On Monday, March 5, 2018 at 10:34:35 AM UTC-5, Volker Dobler wrote:
>>
>> Your two programs are not the same.
>> Try  fmt.Println(bs[0]) instead of len(bs) in the
>> first one. 
>>
>
>> V.
>>
>
> Yes, you are right.
> They are different.
> Their behaviors should be compile dependent. 
>  
>
>>
>> On Monday, 5 March 2018 16:05:05 UTC+1, di...@veryhaha.com wrote:
>>>
>>> Slice:
>>>
>>> package main
>>>
>>> import "fmt"
>>> import "runtime"
>>>
>>> func printMemStat(gcFirstly bool) {
>>> if gcFirstly {
>>> runtime.GC()
>>> }
>>> var stat runtime.MemStats
>>> runtime.ReadMemStats()
>>> println(stat.Alloc)
>>> }
>>>
>>> func main() {
>>> bs := make([]int, 100)
>>> 
>>> printMemStat(false) // about 8071272
>>> printMemStat(true)  // about 67376
>>> // looks the underlying bytes has already
>>> // been garbage collected in the above call.
>>> 
>>> fmt.Println(len(bs))
>>> }
>>>
>>>
>>> Custom type:
>>>
>>> package main
>>>
>>> import "fmt"
>>> import "runtime"
>>>
>>> type T struct {
>>> x int
>>> y *[100]int
>>> }
>>>
>>> func printMemStat(gcFirstly bool) {
>>> if gcFirstly {
>>> runtime.GC()
>>> }
>>> var stat runtime.MemStats
>>> runtime.ReadMemStats()
>>> println(stat.Alloc)
>>> }
>>>
>>> func main() {
>>> t := T{123, new([100]int)}
>>> 
>>> printMemStat(false) // about 8071576
>>> printMemStat(true)  // about 8071576
>>> 
>>> fmt.Println(t.x)
>>> }
>>>
>>

-- 
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: $PATH error.

2018-03-05 Thread Danilo Paes
Dave,

Many thanks!

Now works fine :)

Em segunda-feira, 5 de março de 2018 02:43:19 UTC-3, Dave Cheney escreveu:
>
> Under the hood go get shells out to git to fetch source code. You need to 
> install git. 

-- 
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: Compare values in a for loop that ranges over string array of array

2018-03-05 Thread Ignacio Gómez
Hi, Ashish.

If you have a map[string]int (or int 64, float 64, etc.) "m", doing

m[key] += value


is equivalent to this:

m[key] = m[key] + value.


Thus, on each iteration we sum the value at dataarray[j][1] (which you 
stored at sumFloat) to the current value of sums[dataarray[j][0]] (on first 
iteration, it just gets initialized to the zero value, in this case 0.0) in 
order to sum values among the same letter, which are used as keys for the 
map. So, in short, yes, that's accurate. Take a look at this to get some 
more info on maps: https://blog.golang.org/go-maps-in-action

El lunes, 5 de marzo de 2018, 18:35:11 (UTC-3), Ashish Timilsina escribió:
>
> Hi Ignacio,
>
> This is excellent, works perfectly. Thank you so much. 
> I will try to do my research but just out of curiosity and make sure I 
> understand the code, what does this line do? I also don't have proper 
> understanding of golang maps 
> sums[dataarray[j][0]] += sumFloat
>
>
> So 'sum' map is taking the first index in dataarray as key, summing the 
> second index and assigning it as the value to the key. As it is looping 
> through the array, if it sees that the key is the same, it automatically 
> sums it up? Is that accurate?
>

-- 
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: Compare values in a for loop that ranges over string array of array

2018-03-05 Thread timilsina . ashish . 03
Hi Ignacio,

This is excellent, works perfectly. Thank you so much. 
I will try to do my research but just out of curiosity and make sure I 
understand the code, what does this line do? I also don't have proper 
understanding of golang maps 
sums[dataarray[j][0]] += sumFloat


So 'sum' map is taking the first index in dataarray as key, summing the 
second index and assigning it as the value to the key. As it is looping 
through the array, if it sees that the key is the same, it automatically 
sums it up? Is that accurate?

-- 
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: Array in Structs

2018-03-05 Thread Krzysztof Kowalczyk
A an array in JSON maps to a slice of a given type in Go i.e. []*Foo, where 
Foo is a struct describing the type of array element.

You can read up more on JSON 
mappings: https://www.programming-books.io/essential/go/a-994-json

You can use https://mholt.github.io/json-to-go/ which is a tool where you 
drop your sample .json file and it generates a Go struct definition for you 
that matches the .json file.

-- kjk


On Monday, March 5, 2018 at 10:28:54 AM UTC-8, Pratik Tayshete wrote:
>
> I have a collection in MongoDB in which there is an array of documents for 
> one value. How can I represent this collection in MongoDB in the form of 
> struct in GO. 
>

-- 
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: confusing differences in reflect Type knowledge for a receiver vs. an argument

2018-03-05 Thread Krzysztof Kowalczyk
(in *Inner) InFunc() can't possibly say `in` is Outer.

This piece of code:

var := Outer{}
val.InFunc()

Is really:

val := Outer{}
var tmpInner *Inner = &(val.Inner)
tmpInner.InFunc()

What is passed to InFunc is a pointer to Inner struct embedded inside Outer 
struct, not a pointer to Outer struct.

The compiler did a little bit of magic behind the scenes because it makes 
using struct composition more convenient.

The idea is that if you include Inner struct inside Outer struct, Outer 
"inherits" fields and functions of Inner so syntactically you can say 
outer.Foo() and it will call function defined in Inner() without you having 
to say outer.Inner.Foo().

There's also confusion about what reflection is for.

In (in *Inner) InFoo() you already know the static type of in, which is a 
pointer to struct Inner. There's no need to use reflection.

Reflection is for cases where you have interface type, including the most 
common case of empty interface `interface{}`.

You can convert any value with static type to `interface{}`

var inter interface{} = in // you can convert any static type to interface{}
// code using reflection on inter

// it := in.(InType) // the "obvious" thing fails with: invalid type 
assertion: in.(InType) (non-interface type *Inner on left)

Here you can't use type assertion on `in` because it only works on 
interfaces 
(https://www.programming-books.io/essential/go/a-25362-type-assertion) and 
`in` isn't an interface. The compiler tells you so.

-- kjk

On Monday, March 5, 2018 at 10:28:25 AM UTC-8, Randall O'Reilly wrote:
>
> I'm new to golang, and am hitting some seemingly strange territory that I 
> couldn't find much prior discussion about -- here's one example of the 
> phenomenon in question:
>
>
> https://stackoverflow.com/questions/22153269/how-to-reflect-fields-of-containing-struct-from-a-method-of-the-embedded-struct/49094937#49094937
>
> In brief, it seems that reflect does NOT have access to the "true" 
> underlying type of a struct, when accessing a function receiver struct 
> pointer, but it DOES have access when an object is passed as a regular 
> argument via an interface.  While I understand that the receiver is 
> apparently special in terms of binding to the interface, there is also the 
> statement that it is really just another arg..
>
> In my use-case, I was trying to use reflect to provide some generic tree 
> functionality that could automatically apply to "derived" types that embed 
> a "Node" type with all the tree-relevant functionality.  However, depending 
> on this difference in where the struct appeared (receiver vs. arg) I was 
> variably getting the desired "inheritance" ability to access the fields of 
> the derived types in the base type's code.  In particular, defining a 
> MarshalJSON method for my base type forced everything to be Marshal'd as 
> the base type, not as its actual type -- the generic Marshal gets the 
> struct as an arg, whereas when you define this method you turn it into a 
> receiver!
>
> This issue generally seems relevant to this discussion about the value of 
> struct embedding and the true nature of inheritance in Go: 
> https://github.com/golang/go/issues/22013 -- as someone coming from the 
> C++ world, I find the ability to get at least some basic inheritance 
> functionality to be very powerful, while appreciating the extra flexibility 
> of the compositional / interface model as well.  The example of generic 
> JSON rendering shows how powerful reflection is, *when it can operate on 
> the "true" underlying types* -- this peculiarity with the receivers not 
> having the same "insight" into the true type seems like it should be an 
> easily fixable limitation (to the extent that args really are all the 
> same), and would make the overall behavior more consistent.
>
> Philosophically, Go seems to be "optimized for the lazy" (or elegance if 
> you prefer), which is certainly one of its main advantages compared to C++, 
> but then in the discussion on that proposal, people seem all-too-willing to 
> argue for rewriting a bunch of methods over and over again!  That seems to 
> contradict this core philosophy.  Anyway, someone can hopefully let me know 
> if I should file a bug ticket about this specific inconsistency (or let me 
> know if it already exists somewhere -- I couldn't find it but could have 
> not been using the right terms).
>
> Here's a more succinct example based on above stackoverflow case:
>
> https://play.golang.org/p/KmihXxU19Dd
>
> package main
>
> import (
> "fmt"
> "reflect"
> )
>
> type Inner struct {
> InMbr bool
> }
>
> type InType interface {
> InFun()
> }
>
> type Outer struct {
> Inner
> Id   int
> name string
> }
>
> func (in *Inner) InFun() {
> typ := reflect.TypeOf(in).Elem()
> fmt.Printf("InFun on in always says Inner: %v\n", typ.Name())
> // can I coerce the thing?
> // it := in.(InType) // the "obvious" thing fails with: invalid type 
> assertion: in.(InType) (non-interface type *Inner on 

[go-nuts] Does HTTP/2 Push() send PUSH_PROMISE and data together?

2018-03-05 Thread Eduard Urbach
I have a question regarding the HTTP/2 Pusher interface and how it handles 
PUSH_PROMISE and the data transmission.

>From the comments in the interface code:

// Handlers that wish to push URL X should call Push before sending any
// data that may trigger a request for URL X. This avoids a race where the
// client issues requests for X before receiving the PUSH_PROMISE for X.

This means that the "optimal" way to use it, according to this comment, is 
by calling Push() before sending the HTML document.
However, I measured TTFB to HTML via Google Lighthouse and checked overall 
site performance and it seems that Push() not only sends PUSH_PROMISE but 
also the data when the call happens.
My website is loading much slower than if I put the Push() call after the 
HTML transmission.
This fixes TTFB and the site loads quickly again, but it can occasionally 
lead to data races as described in the comment or in this GitHub gist:

https://gist.github.com/blitzprog/266fb40a8f3811cce183e21cd1b94315

Correct me if I'm wrong, but it seems the Pusher interface gives me only 2 
options:

Variant 1:

1. PUSH_PROMISE
2. Push resource data
3. Write HTML

Variant 2:

1. Write HTML
2. PUSH_PROMISE
3. Push resource data

The actually optimal variant would be...

Variant 3:

1. PUSH_PROMISE
2. Write HTML
3. Push resource data

Am I correct in assuming that the optimal Variant 3 is not possible via the 
HTTP/2 Pusher interface? (I am basing this assumption on the TTFB numbers 
and slow loads when calling Push beforehand)

If that is indeed the case, how can I fix this behavior?
If that is not the case, why is the site loading so much slower and showing 
a much higher TTFB by calling Push() before the HTML transmission?

-- 
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] osx 10.12 all.bash weirdness with os/signal tests

2018-03-05 Thread andrey mirtchovski
Thanks. This will give me a chance to check the new GitHub PR process:
https://github.com/golang/go/pull/24255

On Mon, Mar 5, 2018 at 11:40 AM, Ian Lance Taylor  wrote:
> On Mon, Mar 5, 2018 at 10:10 AM, andrey mirtchovski
>  wrote:
>>
>> I finally found some time to work on this and I think I figured out
>> why it fails. I run a very large history file (my HISTSIZE is set to
>> 10) and on this particular machine I'm at the limit. This causes
>> the os/signal test to run an average 6-7 seconds. The test timeout as
>> shown in my second email seems to be 5 seconds.
>>
>> The easiest way I could find to disable history loading in the bash
>> shell is to set HISTFILE=/dev/null. This reduces the test duration to
>> ~0.2 seconds from ~1.9 seconds. This is sufficient to pass the test:
>>
>> 8<
>> $ go test -run TestTerminalSignal # original
>> PASS
>> ok  os/signal 1.923s
>> $ vi signal_cgo_test.go
>> $ go test -run TestTerminalSignal # with HISTFILE=/dev/null
>> PASS
>> ok  os/signal 0.136s
>> $ git diff .
>> diff --git a/src/os/signal/signal_cgo_test.go 
>> b/src/os/signal/signal_cgo_test.go
>> index 84a2a08ce9..c1cedc7910 100644
>> --- a/src/os/signal/signal_cgo_test.go
>> +++ b/src/os/signal/signal_cgo_test.go
>> @@ -89,6 +89,7 @@ func TestTerminalSignal(t *testing.T) {
>> ctx, cancel := context.WithTimeout(context.Background(), 
>> 10*time.Second)
>> defer cancel()
>> cmd := exec.CommandContext(ctx, bash, "--norc", "--noprofile", "-i")
>> +   cmd.Env = append(os.Environ(), "HISTFILE=/dev/null")
>> cmd.Stdin = slave
>> cmd.Stdout = slave
>> cmd.Stderr = slave
>> 8<
>>
>> If this is an acceptable solution I can prepare a PR on GitHub.
>
> Thanks for figuring this out.  It seems very strange to me that a
> history file could cause the test to take more than 5 seconds.  That
> said, setting HISTFILE is probably a good idea anyhow.  I think it
> should work to set it to the empty string, which would be slightly
> better than /dev/null.  Thanks.
>
> Ian
>
>
>> On Tue, Feb 6, 2018 at 4:20 PM, Ian Lance Taylor  wrote:
>>> On Tue, Feb 6, 2018 at 2:54 PM, andrey mirtchovski
>>>  wrote:
 $ go test -c os/signal
 $ ./signal.test
 PASS
 $ go tool dist test -v

 # Testing packages.
 # go tool dist test -run=^go_test:archive/tar$
 [...]
 ok  net/url (cached)
 ok  os 0.677s
 ok  os/exec 1.414s
 --- FAIL: TestTerminalSignal (5.01s)
 signal_cgo_test.go:138: "PS1='prompt> '\r\n"
 signal_cgo_test.go:163: timed out waiting for shell prompt
 FAIL
 FAIL os/signal 10.104s
 ok  os/user (cached)
 [...]

 At which point I interrupted it. I blew up the entire go repo at and
 cloned it again at tip. This persists.

 $ go version
 go version devel +23e8e197b0 Tue Feb 6 18:24:33 2018 + darwin/amd64
>>>
>>> I'm sorry, I have no idea, and nobody else has reported this.  We
>>> could just disable the test, but it would be nice to see at least one
>>> more report before doing that.
>>>
>>> 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: Compare values in a for loop that ranges over string array of array

2018-03-05 Thread Ignacio Gómez
You can use a map to keep track of a letters sum. Here's your example 
slightly modified (it uses float64 as you were using 
that): https://play.golang.org/p/98L9fDXSN_A

El lunes, 5 de marzo de 2018, 15:28:54 (UTC-3), Ashish Timilsina escribió:
>
> Hi,
>
> I have an array of array string ([][]string{}). I am looping through them 
> and trying to sum the second value of the arrays based on the first value. 
> For example: 
>  a := []string{"a", "1"}
>  a1 := []string{"a", "2"}
>  a2 := []string{"a", "3"}
>  b := []string{"b", "4"}
>  b1 := []string{"b", "1"}
>
> Sum all the 'a' values and 'b' values. 
> Here's the sample code: 
> package main
>
>
> import (
>  "fmt"
>  "log"
>  "strconv"
> )
>
>
> func main() {
>
>
>  a := []string{"a", "1"}
>  a1 := []string{"a", "2"}
>  a2 := []string{"a", "3"}
>  b := []string{"b", "4"}
>  b1 := []string{"b", "2"}
>  b2 := []string{"b", "1"}
>  dataarray := [][]string{}
>  dataarray = append(dataarray, a, a1, a2, b, b1, b2)
>  var totalSum float64
>  for j, _ := range dataarray {
>  sumFloat, err := strconv.ParseFloat(dataarray[j][1], 64)
>  if err != nil {
>  log.Fatal(err)
>  }
>  totalSum += sumFloat
>
>
>  }
>  fmt.Println(totalSum)
> }
>
> Right now, its summing all the values. The result I want is:
> a: 6
> b: 7
>
> Let me know if there's a way to do this. Here's the link to go playground: 
> https://play.golang.org/p/KL8GQ7LPJNi
>
>

-- 
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] How to get an alias in a type alias ???

2018-03-05 Thread Ian Lance Taylor
On Mon, Mar 5, 2018 at 1:35 AM, He Liu  wrote:
>
> package main
>
>
> import (
>
> "log"
>
> "reflect"
>
> )
>
>
> type AAA = int
>
>
> func main() {
>
> var a AAA = 5
>
> x := reflect.TypeOf(a)
>
> log.Println(x.Name())
>
> // print int
>
> }
>
>
> How to get AAA ???

You can't.  A type alias is just another name for a type.  It doesn't
replace the type's real name.  Type aliases only appear at compile
time, not at run time.  If you need the name of a type at run time,
you have to use a real type definition, not a type alias.

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.


Re: [go-nuts] osx 10.12 all.bash weirdness with os/signal tests

2018-03-05 Thread Ian Lance Taylor
On Mon, Mar 5, 2018 at 10:10 AM, andrey mirtchovski
 wrote:
>
> I finally found some time to work on this and I think I figured out
> why it fails. I run a very large history file (my HISTSIZE is set to
> 10) and on this particular machine I'm at the limit. This causes
> the os/signal test to run an average 6-7 seconds. The test timeout as
> shown in my second email seems to be 5 seconds.
>
> The easiest way I could find to disable history loading in the bash
> shell is to set HISTFILE=/dev/null. This reduces the test duration to
> ~0.2 seconds from ~1.9 seconds. This is sufficient to pass the test:
>
> 8<
> $ go test -run TestTerminalSignal # original
> PASS
> ok  os/signal 1.923s
> $ vi signal_cgo_test.go
> $ go test -run TestTerminalSignal # with HISTFILE=/dev/null
> PASS
> ok  os/signal 0.136s
> $ git diff .
> diff --git a/src/os/signal/signal_cgo_test.go 
> b/src/os/signal/signal_cgo_test.go
> index 84a2a08ce9..c1cedc7910 100644
> --- a/src/os/signal/signal_cgo_test.go
> +++ b/src/os/signal/signal_cgo_test.go
> @@ -89,6 +89,7 @@ func TestTerminalSignal(t *testing.T) {
> ctx, cancel := context.WithTimeout(context.Background(), 
> 10*time.Second)
> defer cancel()
> cmd := exec.CommandContext(ctx, bash, "--norc", "--noprofile", "-i")
> +   cmd.Env = append(os.Environ(), "HISTFILE=/dev/null")
> cmd.Stdin = slave
> cmd.Stdout = slave
> cmd.Stderr = slave
> 8<
>
> If this is an acceptable solution I can prepare a PR on GitHub.

Thanks for figuring this out.  It seems very strange to me that a
history file could cause the test to take more than 5 seconds.  That
said, setting HISTFILE is probably a good idea anyhow.  I think it
should work to set it to the empty string, which would be slightly
better than /dev/null.  Thanks.

Ian


> On Tue, Feb 6, 2018 at 4:20 PM, Ian Lance Taylor  wrote:
>> On Tue, Feb 6, 2018 at 2:54 PM, andrey mirtchovski
>>  wrote:
>>> $ go test -c os/signal
>>> $ ./signal.test
>>> PASS
>>> $ go tool dist test -v
>>>
>>> # Testing packages.
>>> # go tool dist test -run=^go_test:archive/tar$
>>> [...]
>>> ok  net/url (cached)
>>> ok  os 0.677s
>>> ok  os/exec 1.414s
>>> --- FAIL: TestTerminalSignal (5.01s)
>>> signal_cgo_test.go:138: "PS1='prompt> '\r\n"
>>> signal_cgo_test.go:163: timed out waiting for shell prompt
>>> FAIL
>>> FAIL os/signal 10.104s
>>> ok  os/user (cached)
>>> [...]
>>>
>>> At which point I interrupted it. I blew up the entire go repo at and
>>> cloned it again at tip. This persists.
>>>
>>> $ go version
>>> go version devel +23e8e197b0 Tue Feb 6 18:24:33 2018 + darwin/amd64
>>
>> I'm sorry, I have no idea, and nobody else has reported this.  We
>> could just disable the test, but it would be nice to see at least one
>> more report before doing that.
>>
>> 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.


Re: [go-nuts] Re: Need help to figure out how to convert user.Current() to string.

2018-03-05 Thread andrey mirtchovski
> var testuser string = string(user.Username)

you don't need the conversion. user.Username is already a string.

-- 
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: Need help to figure out how to convert user.Current() to string.

2018-03-05 Thread john . mizell
I figured out this issue. I was calling the struct and needed to call one 
specific element of the struct. Then I assign it to a string.

user, err := user.Current()
if err != nil {
log.Fatal(err)
}
var testuser string = string(user.Username)
if testuser == "root" || testuser == "someuser" {
fmt.Println("You are currently logged in as:" + testuser 
+":")
}else {
fmt.Println("You need to be root or someuser to run this program")
os.Exit(1)
}


On Monday, March 5, 2018 at 11:28:54 AM UTC-7, John Mizell wrote:
>
>
> Here is the the program
> package main
>
> import (
> "fmt"
> "log"
> "os/user"
> )
>
> func main() {
> username, err := user.Current()
> if err != nil {
> log.Fatal(err)
> }
> if username != "root" || username != "someuser" {
> fmt.Println("You are currently logged in as:" + username)
> fmt.Println("You need to be root or someuser")
> }
>
>
> }
>
> Here is the output
> go run user.go
> # command-line-arguments
> ./user.go:14:14: invalid operation: username != "root" (mismatched types 
> *user.User and string)
> ./user.go:14:36: invalid operation: username != "someuser" (mismatched 
> types *user.User and string)
> ./user.go:15:53: invalid operation: "You are currently logged in as:" + 
> username (mismatched types string and *user.User)
>
> I am not sure how to handle mismatched types string and *user.User. 
>
>

-- 
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] Need help to figure out how to convert user.Current() to string.

2018-03-05 Thread andrey mirtchovski
You have a variable of type *user.User. The documentation
(https://golang.org/pkg/os/user/#User) says there is a field on that
type called "Username". To get the username of a user you should
therefore use username.Username (but that's too stuttery, perhaps "u,
err := user.Current()" and then use u.Username)

-- 
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] High precision timer data?

2018-03-05 Thread Frederic Landais
Hello,

have you considered using time.NewTicker 
 ?

Check the best answer of 
https://stackoverflow.com/questions/16466320/is-there-a-way-to-do-repetitive-tasks-at-intervals-in-golang
 for 
an example

Frederic

-- 
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: Go Games

2018-03-05 Thread nicolas_boiteux via golang-nuts
Hi 

Currently competiting in botters of the galaxy game challenge
https://www.codingame.com/contests/botters-of-the-galaxy

works as other langage.You must now that a part of game development is now 
build directly in integration tools as unity, cry engine, proprietary tools 
that already have their own langage like c#, c++ etc

if you want to use GO, i think you will have to develop from scratch your 
integration tools.

Le lundi 5 mars 2018 01:16:47 UTC+1, Chris FractalBach a écrit :
>
> I'm still new to Go, and have been writing server code to support a 
> multiplayer game.
>
> After reading the Go 2017 Survey Results 
> , I noticed the result* "I 
> work in the following areas: Gaming"* had 5% respondents.
>
> I am curious about general interest in "Go Gaming", and its present & 
> future possibilities!
>

-- 
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] Array in Structs

2018-03-05 Thread pratiktayshete1221
I have a collection in MongoDB in which there is an array of documents for 
one value. How can I represent this collection in MongoDB in the form of 
struct in GO. 

-- 
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] Compare values in a for loop that ranges over string array of array

2018-03-05 Thread timilsina . ashish . 03
Hi,

I have an array of array string ([][]string{}). I am looping through them 
and trying to sum the second value of the arrays based on the first value. 
For example: 
 a := []string{"a", "1"}
 a1 := []string{"a", "2"}
 a2 := []string{"a", "3"}
 b := []string{"b", "4"}
 b1 := []string{"b", "1"}

Sum all the 'a' values and 'b' values. 
Here's the sample code: 
package main


import (
 "fmt"
 "log"
 "strconv"
)


func main() {


 a := []string{"a", "1"}
 a1 := []string{"a", "2"}
 a2 := []string{"a", "3"}
 b := []string{"b", "4"}
 b1 := []string{"b", "2"}
 b2 := []string{"b", "1"}
 dataarray := [][]string{}
 dataarray = append(dataarray, a, a1, a2, b, b1, b2)
 var totalSum float64
 for j, _ := range dataarray {
 sumFloat, err := strconv.ParseFloat(dataarray[j][1], 64)
 if err != nil {
 log.Fatal(err)
 }
 totalSum += sumFloat


 }
 fmt.Println(totalSum)
}

Right now, its summing all the values. The result I want is:
a: 6
b: 7

Let me know if there's a way to do this. Here's the link to go 
playground: https://play.golang.org/p/KL8GQ7LPJNi

-- 
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: Gift wrap errors or not?

2018-03-05 Thread Stratos Neiros
The way I see it, the current best practice is to treat errors as values 
and program with them.

   - https://blog.golang.org/error-handling-and-go
   - https://blog.golang.org/errors-are-values
   - https://www.youtube.com/watch?v=PAAkCSZUG1c=16m13s
   - 
   https://commandcenter.blogspot.com/2017/12/error-handling-in-upspin.html


On Thursday, March 1, 2018 at 10:19:16 PM UTC+2, Tad Vizbaras wrote:
>
> It has been almost two years since this post:
> https://dave.cheney.net/2016/06/12/stack-traces-and-the-errors-package
>
> What is current best practice? Should I use some package to gift wrap 
> errors in order to get stack trace attached to them?
>
> Standard library errors package is really "bare bones". Some guidance 
> would be appreciated.
>

-- 
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] Need help to figure out how to convert user.Current() to string.

2018-03-05 Thread john . mizell

Here is the the program
package main

import (
"fmt"
"log"
"os/user"
)

func main() {
username, err := user.Current()
if err != nil {
log.Fatal(err)
}
if username != "root" || username != "someuser" {
fmt.Println("You are currently logged in as:" + username)
fmt.Println("You need to be root or someuser")
}


}

Here is the output
go run user.go
# command-line-arguments
./user.go:14:14: invalid operation: username != "root" (mismatched types 
*user.User and string)
./user.go:14:36: invalid operation: username != "someuser" (mismatched 
types *user.User and string)
./user.go:15:53: invalid operation: "You are currently logged in as:" + 
username (mismatched types string and *user.User)

I am not sure how to handle mismatched types string and *user.User. 

-- 
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] How to get an alias in a type alias ???

2018-03-05 Thread He Liu


package main


import (

"log"

"reflect"

)


type AAA = int


func main() {

var a AAA = 5

x := reflect.TypeOf(a)

log.Println(x.Name())

// print int

}


How to get AAA ???

-- 
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] confusing differences in reflect Type knowledge for a receiver vs. an argument

2018-03-05 Thread Randall O'Reilly
I'm new to golang, and am hitting some seemingly strange territory that I 
couldn't find much prior discussion about -- here's one example of the 
phenomenon in question:

https://stackoverflow.com/questions/22153269/how-to-reflect-fields-of-containing-struct-from-a-method-of-the-embedded-struct/49094937#49094937

In brief, it seems that reflect does NOT have access to the "true" 
underlying type of a struct, when accessing a function receiver struct 
pointer, but it DOES have access when an object is passed as a regular 
argument via an interface.  While I understand that the receiver is 
apparently special in terms of binding to the interface, there is also the 
statement that it is really just another arg..

In my use-case, I was trying to use reflect to provide some generic tree 
functionality that could automatically apply to "derived" types that embed 
a "Node" type with all the tree-relevant functionality.  However, depending 
on this difference in where the struct appeared (receiver vs. arg) I was 
variably getting the desired "inheritance" ability to access the fields of 
the derived types in the base type's code.  In particular, defining a 
MarshalJSON method for my base type forced everything to be Marshal'd as 
the base type, not as its actual type -- the generic Marshal gets the 
struct as an arg, whereas when you define this method you turn it into a 
receiver!

This issue generally seems relevant to this discussion about the value of 
struct embedding and the true nature of inheritance in Go: 
https://github.com/golang/go/issues/22013 -- as someone coming from the C++ 
world, I find the ability to get at least some basic inheritance 
functionality to be very powerful, while appreciating the extra flexibility 
of the compositional / interface model as well.  The example of generic 
JSON rendering shows how powerful reflection is, *when it can operate on 
the "true" underlying types* -- this peculiarity with the receivers not 
having the same "insight" into the true type seems like it should be an 
easily fixable limitation (to the extent that args really are all the 
same), and would make the overall behavior more consistent.

Philosophically, Go seems to be "optimized for the lazy" (or elegance if 
you prefer), which is certainly one of its main advantages compared to C++, 
but then in the discussion on that proposal, people seem all-too-willing to 
argue for rewriting a bunch of methods over and over again!  That seems to 
contradict this core philosophy.  Anyway, someone can hopefully let me know 
if I should file a bug ticket about this specific inconsistency (or let me 
know if it already exists somewhere -- I couldn't find it but could have 
not been using the right terms).

Here's a more succinct example based on above stackoverflow case:

https://play.golang.org/p/KmihXxU19Dd

package main

import (
"fmt"
"reflect"
)

type Inner struct {
InMbr bool
}

type InType interface {
InFun()
}

type Outer struct {
Inner
Id   int
name string
}

func (in *Inner) InFun() {
typ := reflect.TypeOf(in).Elem()
fmt.Printf("InFun on in always says Inner: %v\n", typ.Name())
// can I coerce the thing?
// it := in.(InType) // the "obvious" thing fails with: invalid type 
assertion: in.(InType) (non-interface type *Inner on left)
// try to obfuscate the process via reflect: (per 
https://groups.google.com/forum/#!msg/Golang-Nuts/KB3_Yj3Ny4c/Ai8tz-nkBwAJ)
vp := reflect.New(typ)
vp.Elem().Set(reflect.ValueOf(in).Elem())
it := vp.Interface().(InType)
ArgFun(it) // no such luck: argfun says "Inner" still
}

func ArgFun(in InType) {
typ := reflect.TypeOf(in).Elem()
fmt.Printf("ArgFun on in tells the truth: %v\n", typ.Name())
}

func main() {
val := Outer{}
val.InFun()
ArgFun()
}

Output: 

InFun on in always says Inner: Inner
ArgFun on in tells the truth: Inner
ArgFun on in tells the truth: Outer


-- 
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] osx 10.12 all.bash weirdness with os/signal tests

2018-03-05 Thread andrey mirtchovski
Hi,

I finally found some time to work on this and I think I figured out
why it fails. I run a very large history file (my HISTSIZE is set to
10) and on this particular machine I'm at the limit. This causes
the os/signal test to run an average 6-7 seconds. The test timeout as
shown in my second email seems to be 5 seconds.

The easiest way I could find to disable history loading in the bash
shell is to set HISTFILE=/dev/null. This reduces the test duration to
~0.2 seconds from ~1.9 seconds. This is sufficient to pass the test:

8<
$ go test -run TestTerminalSignal # original
PASS
ok  os/signal 1.923s
$ vi signal_cgo_test.go
$ go test -run TestTerminalSignal # with HISTFILE=/dev/null
PASS
ok  os/signal 0.136s
$ git diff .
diff --git a/src/os/signal/signal_cgo_test.go b/src/os/signal/signal_cgo_test.go
index 84a2a08ce9..c1cedc7910 100644
--- a/src/os/signal/signal_cgo_test.go
+++ b/src/os/signal/signal_cgo_test.go
@@ -89,6 +89,7 @@ func TestTerminalSignal(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, bash, "--norc", "--noprofile", "-i")
+   cmd.Env = append(os.Environ(), "HISTFILE=/dev/null")
cmd.Stdin = slave
cmd.Stdout = slave
cmd.Stderr = slave
8<

If this is an acceptable solution I can prepare a PR on GitHub.


On Tue, Feb 6, 2018 at 4:20 PM, Ian Lance Taylor  wrote:
> On Tue, Feb 6, 2018 at 2:54 PM, andrey mirtchovski
>  wrote:
>> $ go test -c os/signal
>> $ ./signal.test
>> PASS
>> $ go tool dist test -v
>>
>> # Testing packages.
>> # go tool dist test -run=^go_test:archive/tar$
>> [...]
>> ok  net/url (cached)
>> ok  os 0.677s
>> ok  os/exec 1.414s
>> --- FAIL: TestTerminalSignal (5.01s)
>> signal_cgo_test.go:138: "PS1='prompt> '\r\n"
>> signal_cgo_test.go:163: timed out waiting for shell prompt
>> FAIL
>> FAIL os/signal 10.104s
>> ok  os/user (cached)
>> [...]
>>
>> At which point I interrupted it. I blew up the entire go repo at and
>> cloned it again at tip. This persists.
>>
>> $ go version
>> go version devel +23e8e197b0 Tue Feb 6 18:24:33 2018 + darwin/amd64
>
> I'm sorry, I have no idea, and nobody else has reported this.  We
> could just disable the test, but it would be nice to see at least one
> more report before doing that.
>
> 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: My views on Go and why it's better than Scripting

2018-03-05 Thread dorival . pedroso
Great feedback, Matt and Wang. Thanks and Cheers!



On Monday, March 5, 2018 at 2:13:29 AM UTC-8, Wang Sheng wrote:
>
> I am c++/C expert,  I like because it is easier than C++ and more powerful 
> and flexible than C 
> with Golang , you would not need  consider  create/destroy/monitor pthread 
> ,  crazy pointer is not problem also . 
> as far as I know , most of golanger is  original user of C/C++ 
>
>
>
> 在 2018年3月3日星期六 UTC+8上午5:29:45,dorival...@gmail.com写道:
>>
>> Hi, I could be wrong (please correct me ;-), but here you are what I 
>> think about Go:
>>
>> INTRODUCTION
>> Computers and software were initially developed for scientific computing; 
>> e.g., ALGOL and FORTRAN from the 1950s! Therefore, several computer 
>> languages and libraries have been invented and are used in scientific 
>> computing to date.  Nonetheless, when programming a new scientific 
>> simulation, the question about computational efficiency versus ease-of-use 
>> remains open. Here, we aim to shed light on a suitable answer to this 
>> question---TL;DR use Go and Gosl!
>>
>> One would say that scripting (interpreted) languages might provide the 
>> convenient platform for computations as long as care is taken to send 
>> intensive tasks to functions pre-compiled with high-performance languages. 
>> This strategy fails to create an easy-to-use environment because the 
>> programmer needs to think when and where those tasks should go. Considering 
>> that this kind of decision is essential for performance, we argue that 
>> scripting language is not the best solution.  Furthermore, we argue that 
>> scripting is the worst tool for teaching new programmers in scientific 
>> computing.
>>
>> We argue that only experts should use scripting languages (scripts) for 
>> computer programming because beginners cannot understand how dangerous the 
>> flexibility of scripts can be. For example, the assignment of variables 
>> with the same name to different types is often a cause of misunderstandings 
>> and failures. To make this problem even worse, failures due to wrong types 
>> are not captured at runtime---certainly not at compilation time (there is 
>> no compilation time in scripts). In other words, the interpreter is too 
>> permissive.  The scientist, if aware (rarely the case with students), will 
>> investigate the numerical output and, after much work, will find the source 
>> of the error. Therefore, this situation is not ideal. To exemplify, the 
>> following is allowed in Python (or Julia---similar syntax):
>>
>> ```
>> a = 1.0
>> a = "a" # OK in Python or Julia
>> ```
>>
>> In the following code, Go will detect the error with a message such as 
>> `./test.go:5: cannot use "a" (type string) as type float64 in assignment`:
>>
>> ```
>> package main
>> func main() {
>> a := 1.0
>> a = "a" // not accepted in Go
>> }
>> ```
>>
>> The problem propagates in scripting languages when developing 
>> objected-oriented code. For example, a member data of a class can be 
>> entirely modified by `anyone`, `anywhere` in Python! This issue completely 
>> defeats the purpose of encapsulation in OOP.
>>
>> In summary, scripting (e.g., Python) and alike (e.g., Julia, Matlab) 
>> languages are excellent for the expert programmer only who can understand 
>> what is going on. However, they are very misleading to the beginner. In 
>> other words, the strictness of compiled languages DOES help to learn 
>> computer programming. Furthermore, the tools for working with compiled 
>> language often take advantage of well-defined types. The shift towards type 
>> declaration is so apparent that new languages and strategies are being 
>> invented to overcome these issues. For example, TypeScript and Javascript 
>> (ES6) combined with FlowType have been recently developed and have a fast 
>> adoption among web developers. It seems that no new large project will use 
>> non-typed Javascript code.
>>
>> GO LANGUAGE
>> Go is a modern programming language created by Google engineers in 2007, 
>> including Robert Griesemer, Rob Pike, and Ken Thompson. The language was 
>> later made public as open source in 2009. Go has since grown exponentially 
>> attracting a large number of co-developers and users. The primary goal 
>> leading to the introduction of yet a new language was the combination of 
>> efficiency (like C/C++) with ease of development (like Python). There are 
>> other several innovations and advantages in Go when compared with 
>> mainstream languages such as C/C++/C#/Java/Python/Ruby/Lua. 
>> Also, Go automatically detects Fortran and C files which helps taking 
>> advantage of good existing code.
>>
>> The vocabulary in Go is quite small compared to other languages, making 
>> easy to have an overview of the syntax and available commands. Go avoids 
>> complexities such as generics (aka templates) usually available in other 
>> languages (e.g., C++). Go also tries to avoid unnecessary complexity by not 
>> taking `in the language` 

[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: Why gc compiler treat slice and custom type differently in garbage collection?

2018-03-05 Thread digg


On Monday, March 5, 2018 at 10:34:35 AM UTC-5, Volker Dobler wrote:
>
> Your two programs are not the same.
> Try  fmt.Println(bs[0]) instead of len(bs) in the
> first one. 
>

> V.
>

Yes, you are right.
They are different.
Their behaviors should be compile dependent. 
 

>
> On Monday, 5 March 2018 16:05:05 UTC+1, di...@veryhaha.com wrote:
>>
>> Slice:
>>
>> package main
>>
>> import "fmt"
>> import "runtime"
>>
>> func printMemStat(gcFirstly bool) {
>> if gcFirstly {
>> runtime.GC()
>> }
>> var stat runtime.MemStats
>> runtime.ReadMemStats()
>> println(stat.Alloc)
>> }
>>
>> func main() {
>> bs := make([]int, 100)
>> 
>> printMemStat(false) // about 8071272
>> printMemStat(true)  // about 67376
>> // looks the underlying bytes has already
>> // been garbage collected in the above call.
>> 
>> fmt.Println(len(bs))
>> }
>>
>>
>> Custom type:
>>
>> package main
>>
>> import "fmt"
>> import "runtime"
>>
>> type T struct {
>> x int
>> y *[100]int
>> }
>>
>> func printMemStat(gcFirstly bool) {
>> if gcFirstly {
>> runtime.GC()
>> }
>> var stat runtime.MemStats
>> runtime.ReadMemStats()
>> println(stat.Alloc)
>> }
>>
>> func main() {
>> t := T{123, new([100]int)}
>> 
>> printMemStat(false) // about 8071576
>> printMemStat(true)  // about 8071576
>> 
>> fmt.Println(t.x)
>> }
>>
>

-- 
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 gc compiler treat slice and custom type differently in garbage collection?

2018-03-05 Thread Volker Dobler
Your two programs are not the same.
Try  fmt.Println(bs[0]) instead of len(bs) in the
first one.

V.

On Monday, 5 March 2018 16:05:05 UTC+1, di...@veryhaha.com wrote:
>
> Slice:
>
> package main
>
> import "fmt"
> import "runtime"
>
> func printMemStat(gcFirstly bool) {
> if gcFirstly {
> runtime.GC()
> }
> var stat runtime.MemStats
> runtime.ReadMemStats()
> println(stat.Alloc)
> }
>
> func main() {
> bs := make([]int, 100)
> 
> printMemStat(false) // about 8071272
> printMemStat(true)  // about 67376
> // looks the underlying bytes has already
> // been garbage collected in the above call.
> 
> fmt.Println(len(bs))
> }
>
>
> Custom type:
>
> package main
>
> import "fmt"
> import "runtime"
>
> type T struct {
> x int
> y *[100]int
> }
>
> func printMemStat(gcFirstly bool) {
> if gcFirstly {
> runtime.GC()
> }
> var stat runtime.MemStats
> runtime.ReadMemStats()
> println(stat.Alloc)
> }
>
> func main() {
> t := T{123, new([100]int)}
> 
> printMemStat(false) // about 8071576
> printMemStat(true)  // about 8071576
> 
> fmt.Println(t.x)
> }
>

-- 
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] Why gc compiler treat slice and custom type differently in garbage collection?

2018-03-05 Thread digg
Slice:

package main

import "fmt"
import "runtime"

func printMemStat(gcFirstly bool) {
if gcFirstly {
runtime.GC()
}
var stat runtime.MemStats
runtime.ReadMemStats()
println(stat.Alloc)
}

func main() {
bs := make([]int, 100)

printMemStat(false) // about 8071272
printMemStat(true)  // about 67376
// looks the underlying bytes has already
// been garbage collected in the above call.

fmt.Println(len(bs))
}


Custom type:

package main

import "fmt"
import "runtime"

type T struct {
x int
y *[100]int
}

func printMemStat(gcFirstly bool) {
if gcFirstly {
runtime.GC()
}
var stat runtime.MemStats
runtime.ReadMemStats()
println(stat.Alloc)
}

func main() {
t := T{123, new([100]int)}

printMemStat(false) // about 8071576
printMemStat(true)  // about 8071576

fmt.Println(t.x)
}

-- 
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] best practices of client middleware

2018-03-05 Thread Eyal Posener
Hi

I want to implement a client middleware - for example: sign the request 
body and add the signature as an HTTP header.
I thought that the best way to do it is to implement a RoundTripper 
interface  which up on 
request, calculate the signature, adds the header, and invoke a "next" 
ToundTripper.

This could be a very generic implementation, which i can inject to any 
client that uses the standard library http.Client.

However, I found the following in the doc:

// RoundTrip should not modify the request, except for
// consuming and closing the Request's Body. RoundTrip may
// read fields of the request in a separate goroutine. Callers
// should not mutate the request until the Response's Body has
// been closed.


Is there a standard way to do it?

Thanks,
Eyal

-- 
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] w, x += i, i+i

2018-03-05 Thread Jan Mercl
On Mon, Mar 5, 2018 at 1:42 PM  wrote:


> .. isn't the EBNF at https://golang.org/ref/spec#Assignments currently
wrong - in that it allows what is currently disallowed

The EBNF is just a part of the specification that defines the grammar.
Other parts of the specification often restrict what's allowed based on
semantics, not just grammar.

-- 

-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] w, x += i, i+i

2018-03-05 Thread xiofen77


On Thursday, 1 March 2018 01:45:44 UTC, Ian Lance Taylor wrote:
>
> It was done on purpose, which is to say that there never seemed to be 
> a reason to add it.  It rarely comes up in practice, and it's not 
> obvious whether it's better to support `v1, v2 :+ inc1, inc2` or `v1, 
> v2 += inc` (which adds `inc` to both `v1` and `v2`). 
>
> Ian 
>

 v1, v2 += inc1, inc2 please

matches the pattern for multiple assignment already present

.. isn't the EBNF at https://golang.org/ref/spec#Assignments currently 
wrong - in that it allows what is currently disallowed

.. the correct would be (roughly)

Assignment  = ExpressionList "=" ExpressionList

Assignment_operation = Expression assign_op Expression


 I see the follow on text corrects and clarifies this, but maybe it would 
be better to just split the EBNF def into two lines

-- 
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: My views on Go and why it's better than Scripting

2018-03-05 Thread Wang Sheng
I am c++/C expert,  I like because it is easier than C++ and more powerful 
and flexible than C 
with Golang , you would not need  consider  create/destroy/monitor pthread 
,  crazy pointer is not problem also . 
as far as I know , most of golanger is  original user of C/C++ 



在 2018年3月3日星期六 UTC+8上午5:29:45,dorival...@gmail.com写道:
>
> Hi, I could be wrong (please correct me ;-), but here you are what I think 
> about Go:
>
> INTRODUCTION
> Computers and software were initially developed for scientific computing; 
> e.g., ALGOL and FORTRAN from the 1950s! Therefore, several computer 
> languages and libraries have been invented and are used in scientific 
> computing to date.  Nonetheless, when programming a new scientific 
> simulation, the question about computational efficiency versus ease-of-use 
> remains open. Here, we aim to shed light on a suitable answer to this 
> question---TL;DR use Go and Gosl!
>
> One would say that scripting (interpreted) languages might provide the 
> convenient platform for computations as long as care is taken to send 
> intensive tasks to functions pre-compiled with high-performance languages. 
> This strategy fails to create an easy-to-use environment because the 
> programmer needs to think when and where those tasks should go. Considering 
> that this kind of decision is essential for performance, we argue that 
> scripting language is not the best solution.  Furthermore, we argue that 
> scripting is the worst tool for teaching new programmers in scientific 
> computing.
>
> We argue that only experts should use scripting languages (scripts) for 
> computer programming because beginners cannot understand how dangerous the 
> flexibility of scripts can be. For example, the assignment of variables 
> with the same name to different types is often a cause of misunderstandings 
> and failures. To make this problem even worse, failures due to wrong types 
> are not captured at runtime---certainly not at compilation time (there is 
> no compilation time in scripts). In other words, the interpreter is too 
> permissive.  The scientist, if aware (rarely the case with students), will 
> investigate the numerical output and, after much work, will find the source 
> of the error. Therefore, this situation is not ideal. To exemplify, the 
> following is allowed in Python (or Julia---similar syntax):
>
> ```
> a = 1.0
> a = "a" # OK in Python or Julia
> ```
>
> In the following code, Go will detect the error with a message such as 
> `./test.go:5: cannot use "a" (type string) as type float64 in assignment`:
>
> ```
> package main
> func main() {
> a := 1.0
> a = "a" // not accepted in Go
> }
> ```
>
> The problem propagates in scripting languages when developing 
> objected-oriented code. For example, a member data of a class can be 
> entirely modified by `anyone`, `anywhere` in Python! This issue completely 
> defeats the purpose of encapsulation in OOP.
>
> In summary, scripting (e.g., Python) and alike (e.g., Julia, Matlab) 
> languages are excellent for the expert programmer only who can understand 
> what is going on. However, they are very misleading to the beginner. In 
> other words, the strictness of compiled languages DOES help to learn 
> computer programming. Furthermore, the tools for working with compiled 
> language often take advantage of well-defined types. The shift towards type 
> declaration is so apparent that new languages and strategies are being 
> invented to overcome these issues. For example, TypeScript and Javascript 
> (ES6) combined with FlowType have been recently developed and have a fast 
> adoption among web developers. It seems that no new large project will use 
> non-typed Javascript code.
>
> GO LANGUAGE
> Go is a modern programming language created by Google engineers in 2007, 
> including Robert Griesemer, Rob Pike, and Ken Thompson. The language was 
> later made public as open source in 2009. Go has since grown exponentially 
> attracting a large number of co-developers and users. The primary goal 
> leading to the introduction of yet a new language was the combination of 
> efficiency (like C/C++) with ease of development (like Python). There are 
> other several innovations and advantages in Go when compared with 
> mainstream languages such as C/C++/C#/Java/Python/Ruby/Lua. 
> Also, Go automatically detects Fortran and C files which helps taking 
> advantage of good existing code.
>
> The vocabulary in Go is quite small compared to other languages, making 
> easy to have an overview of the syntax and available commands. Go avoids 
> complexities such as generics (aka templates) usually available in other 
> languages (e.g., C++). Go also tries to avoid unnecessary complexity by not 
> taking `in the language` advanced OOP concepts such as polymorphism, 
> multiple inheritances, and others. Moreover, Go is somewhat pragmatic in 
> the sense that, if an operation can be made much more straightforward, 
> although slightly 

Re: [go-nuts] Channels vs Actors

2018-03-05 Thread Jesper Louis Andersen
To add to Bakul's description:

A key difference in an actor-inspired model compared to a CSP-inspired one
is that identity is subtly different. In Go, channels have identity and can
be referenced. They can have multiple readers and writers. In Erlang, it is
processes who has identity and you can send messages to processes. There
can be multiple senders to the process, but only one process ever receives
from the mailbox. This difference yields subtle differences in the way you
often construct communication, but do note that the models are somewhat
interchangable and what is written in one can be written in the other.
Another subtlety is that multi-writer/single-reader can be targeted for
optimization, and so on.

However, Erlang's message communication is not an implementation of the
Actor model. According to Robert Virding, one of the Erlang authors, they
didn't know about the actor model when they wrote the language, so if
overlap is entirely by accident. Furthermore, Carl Hewitt who proposed the
actor model has a paper in which he explains why Erlang doesn't implement
it: in a pure actor system, you must be able to detect (groups of)
processes who can make no progress ever and garbage collect them. Erlang
doesn't do that.

Erlang's message communication is buffered. Locally, there is no bound on
the message buffer and it is up to the programmer to write appropriate flow
control. Across nodes, connections are by TCP and thus are limited by the
usual TCP window which acts like a buffer: a sender who sends a message on
a 0-window condition is blocked until the delivery can happen.

Crucially, Erlang relies on buffering for its implementation of a selective
receive. You can set up a matching pattern and the mailbox will be
searched, chronologically, until a message in the mailbox matches said
pattern. If no message matches, the process is blocked until one does, or a
timeout.

When a process has identity, you can monitor its lifetime. This is a
central concept in Erlang systems: monitors (or links) are set up between
processes and when they terminate, other processes will have a message
delivered to their mailbox and can thus take action on the event. In Go,
there is no way to find the identity of a goroutine, which yields a
different programming model. Process trees are handled by the "context"
package and lifetime is communicated through a specially constructed "Done"
channel.


On Sun, Mar 4, 2018 at 10:31 PM Bakul Shah  wrote:

> Messages get sent to an actor's address and only that actor “reads”
> from that mailbox. And there is no buffering. Channels don’t run any
> logic (like an actor), they may be buffered and any goroutine with
> access to a channel may read from it. All goroutines run in the same
> address space. As actors don’t share memory, they can be distributed
> or can even migrate from one node to another. Erlang is an actor
> language. Go is not.
>
> On Mar 4, 2018, at 9:00 AM, Anto Aravinth 
> wrote:
>
> Hello All,
>
> I'm new to golang and trying to understand the difference between channels
> and actors. From my knowledge:
>
> 1. Golang support channels, which is concurrently safe
> 2. Channels can be shared across goroutines that are running. (very much
> similar to messages)
>
> Actors:
> 1. They are based on messages.
> 2. Messages are immutable by nature.
> 3. Actors work based on messages, concurrently.
>
> I find actors and channels much similar, may be I'm wrong here. Any help
> would be really good.
>
> Thanks,
> Anto;
>
> --
> 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.
>
> --
> 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.
>

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