Re: [go-nuts] [hooks] go get --post-download "make"

2019-08-09 Thread Dorival Pedroso
ok. I need the other way around (go get => calls make of bash)..

thsnks

On Saturday, August 10, 2019 at 12:15:18 PM UTC+10, saurabh singh wrote:
>
> It's possible to run go get in a make but not the other way around.
> What's your use case? 
>
> On Sat, Aug 10, 2019, 7:07 AM Dorival Pedroso  > wrote:
>
>> Hi, is it possible to run scripts after go get?
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to golan...@googlegroups.com .
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/golang-nuts/bf522c3f-8649-4ef7-a445-fff579d23cf7%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/bf522c3f-8649-4ef7-a445-fff579d23cf7%40googlegroups.com?utm_medium=email_source=footer>
>> .
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/409f61bd-c93e-434e-a6b5-1b01af844ca0%40googlegroups.com.


[go-nuts] [hooks] go get --post-download "make"

2019-08-09 Thread Dorival Pedroso
Hi, is it possible to run scripts after go get?

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/bf522c3f-8649-4ef7-a445-fff579d23cf7%40googlegroups.com.


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

2018-03-09 Thread dorival . pedroso
Thanks for sharing your experience!

On Tuesday, March 6, 2018 at 4:46:54 PM UTC-8, Rich wrote:
>
> I am a systems administrator. I find it easier and faster to write a 
> program in Go than it is to script it in Bash.  Since writing scripts is 
> something most Sys Admins do I've had to write them in Perl, PHP, TCL, 
> Ruby, etc. and the BIGGEST frustration is that I would get a script written 
> debugged etc. and I'd go to deploy it to the server.   The server doesn't 
> use the right version, or doesn't have the right package installed, and 
> hours of additional work are done to get your script to work. On a 
> production server installing one binary for something like a Nagios alarm I 
> can get away with on a production system, I can't just go and start 
> apt-getting or yum installing a bunch of new packages.  With Go I install 
> the dependancies on MY system -- and that system is a Mac.  Cross compiling 
> is trivial (unless the package it used CGO), and I normally generate code 
> that will run on Windows, Linux, Mac and the 32 / 64 bit variations, and I 
> can copy that one binary on to the system. No DLLs, no installing extra 
> packages, it just runs, no dependency or version headaches.
>
> On Friday, March 2, 2018 at 4:29:45 PM UTC-5, dorival...@gmail.com wrote:
>>
>> Hi, I could be wrong (please correct me ;-), but here you are what I 
>> think about 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.


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 

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

2018-03-03 Thread dorival . pedroso
Thanks for your suggestions!

On Saturday, March 3, 2018 at 5:56:41 AM UTC-8, Alex Rice wrote:
>
> Hi, thanks for sharing. I am not convinced about the reasons stated why Go 
> is better than the other languages you mentioned. I am just learning Go, 
> but I have 20 years of experience as a professional developer using various 
> languages. I think students, beginners and professionals should use Go 
> because of it's developer-first attitude. Ergonomics, I've heard it said.
>
> * productivity
> * enjoyment
> * nice workflow and development tools
> * unix philosophy of small chain-able tools
>
> The lissajous example in the the gopl.io [1] book is a great example. In 
> ~50 lines of code, there is a generator of animated gifs of harmonic motion 
> curves, which it serves up on http, or write to standard out. How many 
> lines of code would the same thing be in C, or in Python? I suspect more 
> LOC, and I suspect 3rd party libraries would be involved.
>
> 1. https://github.com/adonovan/gopl.io/blob/master/ch1/lissajous/main.go
>
> Cheers,
> Alex
>
>

-- 
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-02 Thread dorival . pedroso
Thanks for your suggestion!

To put it in context, I'm drafting a plan for my colleagues in order to 
make a case for using Go in teaching instead of Fortran or C.



On Friday, March 2, 2018 at 1:29:45 PM UTC-8, 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 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 orthogonal to the central paradigm, this operation will 
> be carefully defined and adopted in the 

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

2018-03-02 Thread dorival . pedroso
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 orthogonal to the central paradigm, this operation will 
be carefully defined and adopted in the language specification. These 
features, thanks to the unquestionable expertise of the core developers, 
made Go an enjoyable language to work with.

One limitation of some other languages is code organization and package 
development. For example, C/C++ require the use of `#ifndef`, `#define`, 
`#endif`, or `#pragma once` everywhere to prevent code being included more 
than once. In fact, it is 

Re: [go-nuts] Re: error handling needs syntactical sugar

2017-09-08 Thread Dorival Pedroso
Sure! I'm happy to listen to the experience of you all and to keep working 
using the existent approach. Thanks, everyone. Dorival

On Friday, September 8, 2017 at 10:29:02 PM UTC+10, Marvin Renich wrote:
>
> * Dorival Pedroso <ped...@cpmech.com> [170908 02:08]: 
> > The "watch" strategy would, of course, allow us to do the important 
> steps 
> > you've mentioned (e.g. clean up and so on). 
> > 
> > For instance: 
> > watch err != nil { 
> > // do the important things 
> > return err 
> > } 
>
> Except that "do the important things" often depends on which step 
> produced the error.  Now you have a switch statement inside the watch 
> statement to handle the different "early exit" cases.  Instead of having 
> individual "do step1; clean up after step1" in a linear sequence, you 
> have "do step1; do step2..." with all of the separate "clean up after 
> stepN" in a switch statement in a different place.  You also have 
> additional code within the "do step1; do step2..." section to allow the 
> watch statement to determine which switch case to invoke.This is 
> much easier to get wrong, harder to modify (especially if you have 
> nested watch statements), and harder to debug. 
>
> I believe that the Go devs want to encourage suggestions like yours for 
> Go 2, but this particular one has already been discussed more than once 
> on this list.  You have numerous experienced programmers who have all 
> used languages with similar constructs telling you that it looks good at 
> the start, but ends up producing much less maintainable code.  Listen to 
> experience. 
>
> In this particular case, it is not the details that are inconsistent 
> with the basic philosophy behind the design of the Go language, it is 
> the entire concept of separating "error" handling from "non-error" 
> handling.  Both are "handling the results" and both belong in the 
> relative vicinity of the code that produced the results, whether the 
> results are considered "errors" or "non-errors". 
>
> ...Marvin 
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [go-nuts] Re: error handling needs syntactical sugar

2017-09-08 Thread Dorival Pedroso
please replace:
"will return immediately to the [...]"
with
"will jump immediately to the [...]"
(sorry)

On Friday, September 8, 2017 at 4:07:35 PM UTC+10, Dorival Pedroso wrote:
>
> Hi Dave,
>
> The "watch" strategy would, of course, allow us to do the important steps 
> you've mentioned (e.g. clean up and so on).
>
> For instance:
> watch err != nil {
> // do the important things
> return err
> }
>
> The watch basically "groups common tasks".
>
> For example, If we have so many tasks, we could do this:
> watch errFiles != nil {
> cleanup() // do cleanups as Dave suggested
> return // this is an synthetic example that doesn't require error 
> propagation (application dependent, of course)
> }
> watch errComputations != nil {
> // nothing to be done here
> return errComputations // return the error because computations failed
> }
> errFiles = fileOperation("a.txt") // will return immediately to the first 
> "watch" if errFiles != nil
> errFiles = fileOperation("a.txt") // will return immediately to the first 
> "watch" if errFiles != nil
> errFiles = fileOperation("a.txt") // will return immediately to the first 
> "watch" if errFiles != nil
> errCompuations = computeWith("a.txt") // will return immediately to the 
> second "watch" if errComputations != nil
> errCompuations = computeWith("a.txt") // will return immediately to the 
> second "watch" if errComputations != nil
> errCompuations = computeWith("a.txt") // will return immediately to the 
> second "watch" if errComputations != nil
>
> Of course, we don't need the "watch" command for these. In fact, we need 
> nothing special in Go to properly handle these errors.
>
> Cheers.
> Dorival
>
>
>
> On Friday, September 8, 2017 at 1:08:47 PM UTC+10, Dave Cheney wrote:
>>
>>
>>> Wouldn't be great to have a "syntactical sugar" to make things (at least 
>>> a little bit) simpler in our beloved Go language?
>>>
>>>>
>>>>
>> no, I don't think so. 
>>
>> Something that few in in this thread have focused on is the most 
>> important part of the go error handling story happens *before* the `return 
>> err` statement
>>
>> if err != nil {
>>   // this is the important part
>>   return err // this is not
>> }
>>
>> Specifically, when an error occurs, cleaning up the accumulated state to 
>> that point, removing any temporary items like files on disk, transactions, 
>> etc, so that the caller can attempt to retry the operation if they so 
>> choose.
>>
>> Now it happens that most times, thanks to things like defer, there is 
>> usually nothing to handle in the cleanup phase before returning the error, 
>> but in my opinion does not take anything away from this being the most 
>> important part of Go's error handling story. 
>>
>

-- 
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: error handling needs syntactical sugar

2017-09-08 Thread Dorival Pedroso
Hi Dave,

The "watch" strategy would, of course, allow us to do the important steps 
you've mentioned (e.g. clean up and so on).

For instance:
watch err != nil {
// do the important things
return err
}

The watch basically "groups common tasks".

For example, If we have so many tasks, we could do this:
watch errFiles != nil {
cleanup() // do cleanups as Dave suggested
return // this is an synthetic example that doesn't require error 
propagation (application dependent, of course)
}
watch errComputations != nil {
// nothing to be done here
return errComputations // return the error because computations failed
}
errFiles = fileOperation("a.txt") // will return immediately to the first 
"watch" if errFiles != nil
errFiles = fileOperation("a.txt") // will return immediately to the first 
"watch" if errFiles != nil
errFiles = fileOperation("a.txt") // will return immediately to the first 
"watch" if errFiles != nil
errCompuations = computeWith("a.txt") // will return immediately to the 
second "watch" if errComputations != nil
errCompuations = computeWith("a.txt") // will return immediately to the 
second "watch" if errComputations != nil
errCompuations = computeWith("a.txt") // will return immediately to the 
second "watch" if errComputations != nil

Of course, we don't need the "watch" command for these. In fact, we need 
nothing special in Go to properly handle these errors.

Cheers.
Dorival



On Friday, September 8, 2017 at 1:08:47 PM UTC+10, Dave Cheney wrote:
>
>
>> Wouldn't be great to have a "syntactical sugar" to make things (at least 
>> a little bit) simpler in our beloved Go language?
>>
>>>
>>>
> no, I don't think so. 
>
> Something that few in in this thread have focused on is the most important 
> part of the go error handling story happens *before* the `return err` 
> statement
>
> if err != nil {
>   // this is the important part
>   return err // this is not
> }
>
> Specifically, when an error occurs, cleaning up the accumulated state to 
> that point, removing any temporary items like files on disk, transactions, 
> etc, so that the caller can attempt to retry the operation if they so 
> choose.
>
> Now it happens that most times, thanks to things like defer, there is 
> usually nothing to handle in the cleanup phase before returning the error, 
> but in my opinion does not take anything away from this being the most 
> important part of Go's error handling story. 
>

-- 
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: error handling needs syntactical sugar

2017-09-07 Thread Dorival Pedroso
Yes, Nigel! try/catch in Python may at times looks uglier that err != nil. 
I think the reason try/catch didn't bother us in C++ is that we had lots of 
macros to simplify the work...

In Go, we don't have macros but we don't need to wrap things with "try" and 
just need to "recover" panics, I think. That's why I prefer Martin's first 
suggestion (no "wrappings").

Wouldn't be great to have a "syntactical sugar" to make things (at least a 
little bit) simpler in our beloved Go language?

Simpler would certainly encourage people to handle errors properly too as 
Axel pointed out.

Cheers!



On Friday, September 8, 2017 at 9:34:24 AM UTC+10, Nigel Tao wrote:
>
> On Thu, Sep 7, 2017 at 4:00 PM, Tim Uckun  
> wrote: 
> > I don't see anything wrong with the try catch paradigm, 
>
> Try-catch makes for shorter code when you're just passing the buck, 
> but it can be quite complicated when you actually need to handle the 
> buck. 
>
> My showcase example for this is the exception-ridden code in PEP 380 just 
> after 
>
> "The statement 
> RESULT = yield from EXPR 
> is semantically equivalent to" 
>
> https://www.python.org/dev/peps/pep-0380/ 
>
> I find that Python snippet very hard to understand. In contrast, 
> writing all those "if err != nil { return nil, err }" might seem 
> verbose, but I find the control flow much easier to grok, especially 
> when reviewing somebody else's Go code, or even code written by 
> 6-months-ago me. 
>

-- 
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: error handling needs syntactical sugar

2017-09-07 Thread Dorival Pedroso
Agreed, Tim.

This discussion helped me to realise that try/catch is pretty good; e.g. we 
never even bothered discussing this topic in our C++ 
code http://mechsys.nongnu.org/ at all...

In the end of the day, we want to treat ALL errors (obviously...).

Go is great that we have two approaches.

Right now I'm changing my code to panic/recover and it's looking good (so 
far): 
https://github.com/cpmech/gosl/commit/16924f154a848e01a070dc7f86d7f4a3962a0af8

Cheers.
Dorival

On Thursday, September 7, 2017 at 6:37:21 PM UTC+10, Tim Uckun wrote:
>
> Totally not a go programmer but here are my worthless two cents.
>
>
>
> I don't see anything wrong with the try catch paradigm, you can choose 
> your granularity. If you want to check every call then you can, if you want 
> to let a few cluster together you can. You guys make is sound like go style 
> error handling is the only way to catch errors at every step. That's not 
> true at all.  
>
> Surely something can be done about the boilerplate if err != nil  maybe 
> shorten that to iferr or something like that. In fact why can't "err" be a 
> language construct where you raise something and it goes into an err[] 
> array. At any time you can check to see what's in there. That would clean 
> up the code so much.
>
> result = doSomething()
> iferr {
>error = err.pop()
> }
>
> Isn't that so much more readable? 
>
> You could even create checkpoints
>
> raiseErrors()
> // from now on all errors are raised and the program halts
> do()
> some()
> tasks()
> collectErrors()
> // from now on program doesn't halt but err[] array is populated
> do()
> other()
> things()
> dealWithErrArray() // it's global so need to pass it in
> raiseErrors()
> // back to raising them.
>
> As I said none of these are particularly nice.  Elixir gives you both ways 
>
>
> def register({email, password}) do  
>   {:ok, pid} = Membership.connect()
>   sql = "select * from membership.register($1, $2);"
>
>   case Postgrex.Connection.query(pid, sql, [email, password]) do
> {:ok, res} ->
>   cols = res.columns
>   [first_row | _] = res.rows
>   [new_id, validation_token, auth_token, success, message] = first_row
>   {:ok, %RegistrationResult{
> success: success,
> message: message,
> new_id: new_id,
> authentication_token: auth_token,
> validation_token: validation_token
> }}
>
> {:error, err} -> {:error, err}
>   end
> end  
>
>
> try do
>   opts
>   |> Keyword.fetch!(:source_file)
>   |> File.read!
> rescue
>   e in KeyError -> IO.puts "missing :source_file option"
>   e in File.Error -> IO.puts "unable to read source file"
> end
>
> As somebody who has just started learning go I can't find any 
> justification for the insane amount of boilerplate go error handling 
> inflicts on the programmer.  Surely there is a a better way.
>
>
>
> On Wednesday, September 6, 2017 at 8:54:38 PM UTC+12, Henry wrote:
>>
>> I use what I would call as *error context*.
>>
>> Here is the simple definition of the *error context*:
>>
>> type ErrorContext interface {
>> ContainsError() bool
>> SetError(err error)
>> Error() error
>> }
>>
>> Here is how you would use it inside the error-prone function:
>>
>> func FragileFunction(ctx ErrorContext) {
>> if ctx.ContainsError() {
>> return
>> }
>>
>> //some processing ...
>> //if there is an error
>> ctx.SetError(errors.New("some error"))  
>> return
>> }
>>
>>
>> It allows you to do this:
>>
>> ctx := NewErrorContext()
>>
>> fridge := GetFridge(ctx)
>> egg := GetEgg(fridge, ctx) 
>> mixedEgg := MixAndSeason(egg, ctx)
>> friedEgg := Fry(mixedEgg, ctx)
>>
>> if ctx.ContainsError() {
>> fmt.Printf("failed to fry eggs: %s", ctx.Error().Error())
>> }
>>
>> Or you can even do this:
>>
>> ctxA := NewErrorContext()
>> ctxB := NewErrorContext()
>> ignored := NewErrorContext()
>>
>> a := DoSomethingOne(ctxA)
>> b := DoSomethingTwo(a, ctxA)
>> c,d := DoSomethingThree(b, ctxB) //different context
>> if ctxB.ContainsError() {
>>c = 1
>>d = 2
>> }
>> e := DoSomethingFour(c, d, ctxA)
>> if ctxA.ContainsError() {
>> fmt.Println("Failed To do A")
>> }
>>
>> DoSomething(e, ignored) //error is ignored
>>
>> It is up to you how you would implement the error context.
>>
>>
>> On Tuesday, September 5, 2017 at 1:27:20 AM UTC+7, 
>> marti...@programmfabrik.de wrote:
>>
>>> Hi guys,
>>>
>>> at first I though I really like the idea of how Go deals with error 
>>> management and handling, but the more Go code I look at or try to program, 
>>> the more I get scared about checking errors every second line in every 
>>> given block of code.
>>>
>>> Take a look at this example here from "Build Web Application with 
>>> Golang":
>>>
>>> // insert
>>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, 
>>> created) values(?,?,?)")
>>> if err != nil {
>>>   // handle error
>>> }
>>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>>> if err != nil {

Re: [go-nuts] Re: error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
Hi Michael,

I fully agree with handling each single error ("health issue") as they are 
discovered.

The idea of "watch" is NOT to replace this procedure.

It's just a "syntactic sugar" to do what you are doing already.

Cheers.
Dorival 

-- 
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: error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
Since *defer* "is the last thing to happen", I think this code is all right:

func something() (x int, err error) {
watch err != nil {
return
}
res, err = acquireResource()
defer func() {
if err == nil {
err = res.Close()
}
}()
err = abc1()
err = abc2()
err = abc3()
err = abc4()
}

Also, I'd like to make a general comment (not specific to this case). The 
*watch* command doesn't seem (to me) a bad idea. And it could be used for 
other purposes too (e.g. as the "watch expression" feature in debuggers or 
for logging---yeah we don't really need it...).

For instance:

func calculations() {
x := 100.0
watch x < 0 {
fmt.Printf("hey, x is negative (%d)\n", x)
fmt.Printf("...no worries...\n")
}
x = compute(1,2,3)
x = compute(3,2,1)
x = compute(1,3,2)
}

It's of course NOT needed at all. Above, we can do the same thing in a 
different (probably better) way.

In fact, *Go is perfect the way it is* and doesn't need any change at all!

Also, the mechanics (implementation) of *watch* may be "impossible", "too 
hard", "confusing" or at least "inefficient"---I don't know (no idea...).

With an opportunity to work on the Go language implementation, I would 
rather spend some time tweaking things to be faster...

Cheers!
Dorival

On Wednesday, September 6, 2017 at 1:11:36 AM UTC+10, eko...@gmail.com 
wrote:
>
> I've been doing something like this for long chains where "handle error" 
> is the same:
>
> func something() (x int, err error) {
> defer func() {
> if err != nil {
> // handle error
> }
> }()
> res, err = acquireResource()
> if err == nil {
> defer func() {
> if e := res.Close(); err == nil {
> err = e
> }
> }()
> err = abc1()
> }
> if err == nil {
> err = abc2()
> }
> if err == nil {
> err = abc3()
> }
> if err == nil {
> err = abc4()
> }
> }
>
> How would watch interact with defer?
>
> On Monday, September 4, 2017 at 8:27:20 PM UTC+2, 
> marti...@programmfabrik.de wrote:
>>
>> Hi guys,
>>
>> at first I though I really like the idea of how Go deals with error 
>> management and handling, but the more Go code I look at or try to program, 
>> the more I get scared about checking errors every second line in every 
>> given block of code.
>>
>> Take a look at this example here from "Build Web Application with Golang":
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) 
>> values(?,?,?)")
>> if err != nil {
>>   // handle error
>> }
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> if err != nil {
>>   // handle error
>> }
>> id, err := res.LastInsertId()
>> if err != nil {
>>   // handle error
>> }
>> fmt.Println(id)
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> if err != nil {
>>   // handle error
>> }
>> res, err = stmt.Exec("astaxieupdate", id)
>> if err != nil {
>>   // handle error
>> }
>> affect, err := res.RowsAffected()
>> if err != nil {
>>   // handle error
>> }
>>
>>
>> Seriously? And yes, I have read 
>> https://blog.golang.org/errors-are-values...
>>
>> The best case reduction I found is:
>>
>> ...
>> res, err = stmt.Exec("astaxieupdate", id)
>> checkError(err)
>> ...
>>
>> Still, I need this after each line of calling a function which may return 
>> an error.
>>
>> I bet this is not pleasant to do in larger code bases and it also takes 
>> away focus from what is actually happening.
>>
>> 50-80% of all lines of code in my example deal with error handling?
>>
>> This is not good. Seriously.
>>
>> And don't get me wrong, there is a lot of things I really like, love and 
>> adore about Go, but catching errors needs an improved syntax!
>>
>> And I am not proposing try...catch here. 
>>
>> How about introducing a new piece of syntax 
>>
>> "watch if   " 
>>
>> which tells the compiler to watch out for changes in a given SimpleStmt
>>
>> The same code as above would look like this:
>>
>> var err Error
>>
>> watch if err != nil {
>>   // handle error(s)
>> }
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, 
>> created) values(?,?,?)")
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> id, err := res.LastInsertId()
>> fmt.Println(id)
>>
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> res, err = stmt.Exec("astaxieupdate", id)
>> affect, err := res.RowsAffected()
>>
>>
>>- The "watch if" would be executed after each assignment of any of 
>>the variables used in SimpleStmt of the statement.
>>- Multiple "watch if" would be executed in order or appearance
>>- The "watch if" could be used like "defer..." inside functions
>>- The "watch if" would work in its full scope of the watched variables
>>
>> I am not a language expert, so may be 

[go-nuts] Re: error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
Hi, yes we need the check condition you had before in defer. That seems fine. 
But there may be some other problems I haven't thought of. Cheers 

-- 
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: error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
What about?

func something() (x int, err error) {
watch err != nil { // this is only required to watch out in case "err" 
ever becomes non-nil
return // the error will propagate outside (same as "return err")
}
res, err = acquireResource() // will return straightway (because we 
cannot close the resource...)
defer func() {
e := res.Close()
return 0, e
}()
err = abc1() // if err != nil, the "watcher" would return right here 
with the most recent error (message)
err = abc2() // This seems better than "accumulating" the error in 
an internal data structure
err = abc3() // because abc2() and so on wouldn't even work if 
abc1() had failed
err = abc4() // But of course, another err1, err2, ... could be 
used instead
}

(Again, just an idea...)
Cheers!

On Wednesday, September 6, 2017 at 1:11:36 AM UTC+10, eko...@gmail.com 
wrote:
>
> I've been doing something like this for long chains where "handle error" 
> is the same:
>
> func something() (x int, err error) {
> defer func() {
> if err != nil {
> // handle error
> }
> }()
> res, err = acquireResource()
> if err == nil {
> defer func() {
> if e := res.Close(); err == nil {
> err = e
> }
> }()
> err = abc1()
> }
> if err == nil {
> err = abc2()
> }
> if err == nil {
> err = abc3()
> }
> if err == nil {
> err = abc4()
> }
> }
>
> How would watch interact with defer?
>
> On Monday, September 4, 2017 at 8:27:20 PM UTC+2, 
> marti...@programmfabrik.de wrote:
>>
>> Hi guys,
>>
>> at first I though I really like the idea of how Go deals with error 
>> management and handling, but the more Go code I look at or try to program, 
>> the more I get scared about checking errors every second line in every 
>> given block of code.
>>
>> Take a look at this example here from "Build Web Application with Golang":
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) 
>> values(?,?,?)")
>> if err != nil {
>>   // handle error
>> }
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> if err != nil {
>>   // handle error
>> }
>> id, err := res.LastInsertId()
>> if err != nil {
>>   // handle error
>> }
>> fmt.Println(id)
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> if err != nil {
>>   // handle error
>> }
>> res, err = stmt.Exec("astaxieupdate", id)
>> if err != nil {
>>   // handle error
>> }
>> affect, err := res.RowsAffected()
>> if err != nil {
>>   // handle error
>> }
>>
>>
>> Seriously? And yes, I have read 
>> https://blog.golang.org/errors-are-values...
>>
>> The best case reduction I found is:
>>
>> ...
>> res, err = stmt.Exec("astaxieupdate", id)
>> checkError(err)
>> ...
>>
>> Still, I need this after each line of calling a function which may return 
>> an error.
>>
>> I bet this is not pleasant to do in larger code bases and it also takes 
>> away focus from what is actually happening.
>>
>> 50-80% of all lines of code in my example deal with error handling?
>>
>> This is not good. Seriously.
>>
>> And don't get me wrong, there is a lot of things I really like, love and 
>> adore about Go, but catching errors needs an improved syntax!
>>
>> And I am not proposing try...catch here. 
>>
>> How about introducing a new piece of syntax 
>>
>> "watch if   " 
>>
>> which tells the compiler to watch out for changes in a given SimpleStmt
>>
>> The same code as above would look like this:
>>
>> var err Error
>>
>> watch if err != nil {
>>   // handle error(s)
>> }
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, 
>> created) values(?,?,?)")
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> id, err := res.LastInsertId()
>> fmt.Println(id)
>>
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> res, err = stmt.Exec("astaxieupdate", id)
>> affect, err := res.RowsAffected()
>>
>>
>>- The "watch if" would be executed after each assignment of any of 
>>the variables used in SimpleStmt of the statement.
>>- Multiple "watch if" would be executed in order or appearance
>>- The "watch if" could be used like "defer..." inside functions
>>- The "watch if" would work in its full scope of the watched variables
>>
>> I am not a language expert, so may be there is a saner way of expression 
>> what I want to achieve.
>>
>> But bottom line is, there should by an easier to read and write way to 
>> deal with errors in Go.
>>
>>
>> Martin
>>
>>
>>
>>
>>
>>

-- 
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: error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
What about the following?

func something() (x int, err error) {
watch err != nil { // this is only required to watch out in case "err" 
ever becomes non-nil
return // the error will propagate outside (same as "return err")
}
res, err = acquireResource() // will return straightway (because we 
cannot close the resource...)
defer func() {
e := res.Close() // if err != nil, the "watcher" would return the 
message
return 0, e
}()
err = abc1() // if err != nil, the "watcher" would return right here 
with the most recent error (message)
err = abc2() // This seems better than "accumulating" the error in 
an internal data structure
err = abc3() // because abc2() and so on wouldn't even work if 
abc1() had failed
err = abc4() // But of course, another err1, err2, ... could be 
used instead
}

(again, just an idea...)
Cheers!


On Wednesday, September 6, 2017 at 1:11:36 AM UTC+10, eko...@gmail.com 
wrote:
>
> I've been doing something like this for long chains where "handle error" 
> is the same:
>
> func something() (x int, err error) {
> defer func() {
> if err != nil {
> // handle error
> }
> }()
> res, err = acquireResource()
> if err == nil {
> defer func() {
> if e := res.Close(); err == nil {
> err = e
> }
> }()
> err = abc1()
> }
> if err == nil {
> err = abc2()
> }
> if err == nil {
> err = abc3()
> }
> if err == nil {
> err = abc4()
> }
> }
>
> How would watch interact with defer?
>
> On Monday, September 4, 2017 at 8:27:20 PM UTC+2, 
> marti...@programmfabrik.de wrote:
>>
>> Hi guys,
>>
>> at first I though I really like the idea of how Go deals with error 
>> management and handling, but the more Go code I look at or try to program, 
>> the more I get scared about checking errors every second line in every 
>> given block of code.
>>
>> Take a look at this example here from "Build Web Application with Golang":
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) 
>> values(?,?,?)")
>> if err != nil {
>>   // handle error
>> }
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> if err != nil {
>>   // handle error
>> }
>> id, err := res.LastInsertId()
>> if err != nil {
>>   // handle error
>> }
>> fmt.Println(id)
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> if err != nil {
>>   // handle error
>> }
>> res, err = stmt.Exec("astaxieupdate", id)
>> if err != nil {
>>   // handle error
>> }
>> affect, err := res.RowsAffected()
>> if err != nil {
>>   // handle error
>> }
>>
>>
>> Seriously? And yes, I have read 
>> https://blog.golang.org/errors-are-values...
>>
>> The best case reduction I found is:
>>
>> ...
>> res, err = stmt.Exec("astaxieupdate", id)
>> checkError(err)
>> ...
>>
>> Still, I need this after each line of calling a function which may return 
>> an error.
>>
>> I bet this is not pleasant to do in larger code bases and it also takes 
>> away focus from what is actually happening.
>>
>> 50-80% of all lines of code in my example deal with error handling?
>>
>> This is not good. Seriously.
>>
>> And don't get me wrong, there is a lot of things I really like, love and 
>> adore about Go, but catching errors needs an improved syntax!
>>
>> And I am not proposing try...catch here. 
>>
>> How about introducing a new piece of syntax 
>>
>> "watch if   " 
>>
>> which tells the compiler to watch out for changes in a given SimpleStmt
>>
>> The same code as above would look like this:
>>
>> var err Error
>>
>> watch if err != nil {
>>   // handle error(s)
>> }
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, 
>> created) values(?,?,?)")
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> id, err := res.LastInsertId()
>> fmt.Println(id)
>>
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> res, err = stmt.Exec("astaxieupdate", id)
>> affect, err := res.RowsAffected()
>>
>>
>>- The "watch if" would be executed after each assignment of any of 
>>the variables used in SimpleStmt of the statement.
>>- Multiple "watch if" would be executed in order or appearance
>>- The "watch if" could be used like "defer..." inside functions
>>- The "watch if" would work in its full scope of the watched variables
>>
>> I am not a language expert, so may be there is a saner way of expression 
>> what I want to achieve.
>>
>> But bottom line is, there should by an easier to read and write way to 
>> deal with errors in Go.
>>
>>
>> Martin
>>
>>
>>
>>
>>
>>

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

[go-nuts] Re: error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
What about the following?

func something() (x int, err error) {
watch err != nil { // this is only required to watch out in case "err" 
ever becomes non-nil
return // the error will propagate outside (same as "return err")
}
res, err = acquireResource() // will return straightway? (because we 
cannot close the
 // resource...)
defer func() {
e := res.Close() // if err != nil, the "watcher" would return the 
message
return 0, e
}()
err = abc1() // if err != nil, the "watcher" would return right here 
with the most recent error (message)
err = abc2() // This seems better than "accumulating" the error in 
an internal data structure
err = abc3() // because abc2() and so on wouldn't even work if 
abc1() had failed
err = abc4() // But of course, another err1, err2, ... could be 
used instead
}

There might be something wrong in the code above (sorry)... don't know...
Again...just an idea...
Cheers.
Dorival



On Wednesday, September 6, 2017 at 1:11:36 AM UTC+10, eko...@gmail.com 
wrote:
>
> I've been doing something like this for long chains where "handle error" 
> is the same:
>
> func something() (x int, err error) {
> defer func() {
> if err != nil {
> // handle error
> }
> }()
> res, err = acquireResource()
> if err == nil {
> defer func() {
> if e := res.Close(); err == nil {
> err = e
> }
> }()
> err = abc1()
> }
> if err == nil {
> err = abc2()
> }
> if err == nil {
> err = abc3()
> }
> if err == nil {
> err = abc4()
> }
> }
>
> How would watch interact with defer?
>
> On Monday, September 4, 2017 at 8:27:20 PM UTC+2, 
> marti...@programmfabrik.de wrote:
>>
>> Hi guys,
>>
>> at first I though I really like the idea of how Go deals with error 
>> management and handling, but the more Go code I look at or try to program, 
>> the more I get scared about checking errors every second line in every 
>> given block of code.
>>
>> Take a look at this example here from "Build Web Application with Golang":
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) 
>> values(?,?,?)")
>> if err != nil {
>>   // handle error
>> }
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> if err != nil {
>>   // handle error
>> }
>> id, err := res.LastInsertId()
>> if err != nil {
>>   // handle error
>> }
>> fmt.Println(id)
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> if err != nil {
>>   // handle error
>> }
>> res, err = stmt.Exec("astaxieupdate", id)
>> if err != nil {
>>   // handle error
>> }
>> affect, err := res.RowsAffected()
>> if err != nil {
>>   // handle error
>> }
>>
>>
>> Seriously? And yes, I have read 
>> https://blog.golang.org/errors-are-values...
>>
>> The best case reduction I found is:
>>
>> ...
>> res, err = stmt.Exec("astaxieupdate", id)
>> checkError(err)
>> ...
>>
>> Still, I need this after each line of calling a function which may return 
>> an error.
>>
>> I bet this is not pleasant to do in larger code bases and it also takes 
>> away focus from what is actually happening.
>>
>> 50-80% of all lines of code in my example deal with error handling?
>>
>> This is not good. Seriously.
>>
>> And don't get me wrong, there is a lot of things I really like, love and 
>> adore about Go, but catching errors needs an improved syntax!
>>
>> And I am not proposing try...catch here. 
>>
>> How about introducing a new piece of syntax 
>>
>> "watch if   " 
>>
>> which tells the compiler to watch out for changes in a given SimpleStmt
>>
>> The same code as above would look like this:
>>
>> var err Error
>>
>> watch if err != nil {
>>   // handle error(s)
>> }
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, 
>> created) values(?,?,?)")
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> id, err := res.LastInsertId()
>> fmt.Println(id)
>>
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> res, err = stmt.Exec("astaxieupdate", id)
>> affect, err := res.RowsAffected()
>>
>>
>>- The "watch if" would be executed after each assignment of any of 
>>the variables used in SimpleStmt of the statement.
>>- Multiple "watch if" would be executed in order or appearance
>>- The "watch if" could be used like "defer..." inside functions
>>- The "watch if" would work in its full scope of the watched variables
>>
>> I am not a language expert, so may be there is a saner way of expression 
>> what I want to achieve.
>>
>> But bottom line is, there should by an easier to read and write way to 
>> deal with errors in Go.
>>
>>
>> Martin
>>
>>
>>
>>
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from 

Re: [go-nuts] error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
Wojciech, you're right: It'll effectively work as a "catch" (or "recover"); 
e.g. something like:

defer func() {
if err := recover(); err != nil {
fmt.Printf("ERROR: %v\n", err)
}
}()

The only difference is that we wouldn't have to "throw" or "panic". The 
compiler would just "watch" the "behaviour" of the error variable.

But, hey, I think we're all very happy with the options we have to handle 
errors in Go: we have the "error" keyword AND panic/recover! That's great!

Also, I think we're just wondering whether a "syntactical sugar" is worth 
in Go or not (speaking for myself, of course).

Best wishes.
Dorival

On Tuesday, September 5, 2017 at 11:07:12 PM UTC+10, ohir wrote:
>
> On Tue, 5 Sep 2017 00:20:09 -0700 (PDT) 
> Dorival Pedroso <ped...@cpmech.com > wrote: 
>
> > I realised I've written 569 "if err != nil": 
> > And I've written 231 error messages 
> > And I have a feeling that I've done only 20% of the error messages... 
>
> Factor 2,46 so far. 
>
> It directly *proves* that any 'watch' construct would get us soon to 
> 'spooky 
> action at distance' at massive scale. What is now written just after call 
> would get a trip to some distant watch block and be 'cased' there. 
>
> So why call it 'watch' at all? It would be simply a 'catch' :) 
>   
> BAD. 
>
> > See the messages 
> > here: https://gist.github.com/cpmech/d2e36dcbe277cd72605f3732d79c798b 
>
>
> -- 
> Wojciech S. Czarnecki 
>  << ^oo^ >> OHIR-RIPE 
>

-- 
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: error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
Thanks again, Rob.

The blog post (https://blog.golang.org/errors-are-values) does shed some 
light.

One of the ideas is to hold the *err* variable in a structure. I will 
definitively use this more often (I do have many structures and never 
thought of doing this!)---Thanks!

The other idea is to create a wrapping structure (e.g. type errWriter struct 
{w io.Writer; err error}) just to keep hold of the *err* variable. In this 
case, I'd prefer to return *err* in my "pure function" (I also have many of 
those; e.g. for "mathematical computations"). In this case, I actually 
don't mind returning and checking the err variable as long as I don't need 
the wrapper.

Now, this piece of code:

ew := {w: fd}
ew.write(p0[a:b])
ew.write(p1[c:d])
ew.write(p2[e:f])
// and so on
if ew.err != nil {
return ew.err
}


could easily (?, I don't know) be replaced by:

*watch* err != nil {

return err

}
err = fd.write(p0[a:b])
err = fd.write(p1[c:d])
err = fd.write(p2[e:f])
// and so on


and we wouldn't need the wrapping structure... (sorry for being so lazy ;-)

By the way, maybe one day I'll attend a GoCon and will bring a laptop for 
sure...

Cheers.
Dorival


On Tuesday, September 5, 2017 at 6:39:05 PM UTC+10, Rob 'Commander' Pike 
wrote:
>
> If you find that lines like if err != nil are a significant fraction 
> of non-test code, your code probably needs a better error handling 
> strategy, not a language change. I have done measurements in the past 
> and although people complain a lot about the presence of that 
> statement, it shows up much less often in practice than people claim, 
> and when it does appear a lot it's usually because the programmer is 
> not thinking enough about how errors should work. 
>
> Please reread that blog post. 
>
> -rob 
>
>
> On Tue, Sep 5, 2017 at 5:45 PM, Dorival Pedroso <ped...@cpmech.com 
> > wrote: 
> > Fair enough. This would be perfect. Cheers 
> > 
> > 
> > On Tuesday, September 5, 2017 at 5:42:26 PM UTC+10, 
> > marti...@programmfabrik.de wrote: 
> >> 
> >> Dorival, 
> >> 
> >> I think we can celebrate already if we achieve anything with this 
> >> discussion. Let's not ask for too much, plus let's not make it too 
> >> complicated. 
> >> 
> >> I think your proposed "watch err", hides too much and does too little. 
> >> 
> >> You can simply write (the inline code editor is broken, BTW) 
> >> 
> >> func ... { 
> >> var err 
> >> watch err != nil { 
> >> // handle error 
> >> return 
> >> } 
> >> // do stuff 
> >> yo1, err := do_stuff1() 
> >> yo2, err := do_stuff2() 
> >> yo3, err := do_stuff3() 
> >> } 
> >> 
> >> 
> >> Martin 
> >> 
> >> 
> >> On Tuesday, September 5, 2017 at 9:32:50 AM UTC+2, Dorival Pedroso 
> wrote: 
> >>> 
> >>> Hi Martin; 
> >>> 
> >>> What about two commands "watch" and "watchif"? 
> >>> 
> >>> The first works as the "var" command and the second as the "if" 
> command. 
> >>> 
> >>> "watch" does: 
> >>> 
> >>> In a function with error as an output (anywhere): returns in case the 
> err 
> >>> declared with watch err (or watch myerror) becomes non-nil. watch err 
> would 
> >>> declare err" as var does. Most use cases would put watch err at the 
> >>> beginning of a function (although this is optional as it is with 
> defer) 
> >>> In a test function; aka TestSomething(something *testing.T), watch err 
> >>> error would declare err (or watch myerror error) and if an error 
> occurs, it 
> >>> would call something.FailNow() after (printing the error 
> message?---still 
> >>> need to think this part better) 
> >>> In the main function: watch err error would print the error message 
> (or 
> >>> maybe pipe to stderr) and os.Exist(1) 
> >>> watchif err != nil {HERE} would be more powerful because it would 
> allow 
> >>> us to do other things. But the mechanism is similar (as you proposed 
> >>> initially): if err becomes non-nil anywhere, the execution in HERE 
> would 
> >>> take place. 
> >>> 
> >>> Cheers! 
> >>> 
> >>> 
> >>> On Tuesday, September 5, 2017 at 4:55:59 PM UTC+10, 
> >>> marti...@programmfabrik.de wrote: 
> >>>> 
> >>>> Hi Dorival, 
> >>>> 
> >>>> thanks for supporting me with m

Re: [go-nuts] Re: error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
Exactly: a good amount of "if err != nil" appears in my tests (334 out of 
569). I'll try to re-think the other cases... 
(e.g. https://github.com/cpmech/gosl/blob/master/la/blas2.go)

No complaints here, by the way! Just enjoying this marvellous language!

I'll read the blog post.
Cheers.

On Tuesday, September 5, 2017 at 6:39:05 PM UTC+10, Rob 'Commander' Pike 
wrote:
>
> If you find that lines like if err != nil are a significant fraction 
> of non-test code, your code probably needs a better error handling 
> strategy, not a language change. I have done measurements in the past 
> and although people complain a lot about the presence of that 
> statement, it shows up much less often in practice than people claim, 
> and when it does appear a lot it's usually because the programmer is 
> not thinking enough about how errors should work. 
>
> Please reread that blog post. 
>
> -rob 
>
>
> On Tue, Sep 5, 2017 at 5:45 PM, Dorival Pedroso <ped...@cpmech.com 
> > wrote: 
> > Fair enough. This would be perfect. Cheers 
> > 
> > 
> > On Tuesday, September 5, 2017 at 5:42:26 PM UTC+10, 
> > marti...@programmfabrik.de wrote: 
> >> 
> >> Dorival, 
> >> 
> >> I think we can celebrate already if we achieve anything with this 
> >> discussion. Let's not ask for too much, plus let's not make it too 
> >> complicated. 
> >> 
> >> I think your proposed "watch err", hides too much and does too little. 
> >> 
> >> You can simply write (the inline code editor is broken, BTW) 
> >> 
> >> func ... { 
> >> var err 
> >> watch err != nil { 
> >> // handle error 
> >> return 
> >> } 
> >> // do stuff 
> >> yo1, err := do_stuff1() 
> >> yo2, err := do_stuff2() 
> >> yo3, err := do_stuff3() 
> >> } 
> >> 
> >> 
> >> Martin 
> >> 
> >> 
> >> On Tuesday, September 5, 2017 at 9:32:50 AM UTC+2, Dorival Pedroso 
> wrote: 
> >>> 
> >>> Hi Martin; 
> >>> 
> >>> What about two commands "watch" and "watchif"? 
> >>> 
> >>> The first works as the "var" command and the second as the "if" 
> command. 
> >>> 
> >>> "watch" does: 
> >>> 
> >>> In a function with error as an output (anywhere): returns in case the 
> err 
> >>> declared with watch err (or watch myerror) becomes non-nil. watch err 
> would 
> >>> declare err" as var does. Most use cases would put watch err at the 
> >>> beginning of a function (although this is optional as it is with 
> defer) 
> >>> In a test function; aka TestSomething(something *testing.T), watch err 
> >>> error would declare err (or watch myerror error) and if an error 
> occurs, it 
> >>> would call something.FailNow() after (printing the error 
> message?---still 
> >>> need to think this part better) 
> >>> In the main function: watch err error would print the error message 
> (or 
> >>> maybe pipe to stderr) and os.Exist(1) 
> >>> watchif err != nil {HERE} would be more powerful because it would 
> allow 
> >>> us to do other things. But the mechanism is similar (as you proposed 
> >>> initially): if err becomes non-nil anywhere, the execution in HERE 
> would 
> >>> take place. 
> >>> 
> >>> Cheers! 
> >>> 
> >>> 
> >>> On Tuesday, September 5, 2017 at 4:55:59 PM UTC+10, 
> >>> marti...@programmfabrik.de wrote: 
> >>>> 
> >>>> Hi Dorival, 
> >>>> 
> >>>> thanks for supporting me with my idea. 
> >>>> 
> >>>> And yes, after writing my post yesterday I was thinking, "watchif" or 
> >>>> even simply "watch". 
> >>>> 
> >>>> And yes, today I am more in favor of simply "watch". 
> >>>> 
> >>>> And yes, we can constrain this to the context of one function (like 
> >>>> defer), I am ok with that. 
> >>>> 
> >>>> What you are describing how you work with errors and how you spent 
> hours 
> >>>> adding 
> >>>> 
> >>>> if err != nil 
> >>>> 
> >>>> that is exactly my point. 
> >>>> 
> >>>> On could nicely write this 
> >>>> 
> >>>> ... 
> >>>> watch err!=nil { 
> >>>>   handle_sql_error(err) 
> >>>> } 
> >>>> ... 
> >>>> 
> >>>> Of course, watch could also be used to not watch out for errors but 
> any 
> >>>> other places where new values to get assigned to variables. 
> >>>> 
> >>>> Martin 
> >>>>>> 
> >>>>>> 
> > -- 
> > You received this message because you are subscribed to the Google 
> Groups 
> > "golang-nuts" group. 
> > To unsubscribe from this group and stop receiving emails from it, send 
> an 
> > email to golang-nuts...@googlegroups.com . 
> > For more options, visit https://groups.google.com/d/optout. 
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
Fair enough. This would be perfect. Cheers

On Tuesday, September 5, 2017 at 5:42:26 PM UTC+10, 
marti...@programmfabrik.de wrote:
>
> Dorival,
>
> I think we can celebrate already if we achieve anything with this 
> discussion. Let's not ask for too much, plus let's not make it too 
> complicated.
>
> I think your proposed "watch err", hides too much and does too little.
>
> You can simply write (the inline code editor is broken, BTW)
>
> func ... {
> var err
> watch err != nil {
> // handle error
> return
> }
> // do stuff
> yo1, err := do_stuff1()
> yo2, err := do_stuff2()
> yo3, err := do_stuff3()
> }
>
>
> Martin
>
>
> On Tuesday, September 5, 2017 at 9:32:50 AM UTC+2, Dorival Pedroso wrote:
>>
>> Hi Martin;
>>
>> What about two commands "*watch*" and "*watchif*"?
>>
>> The first works as the "*var*" command and the second as the "*if*" 
>> command.
>>
>> "*watch*" does:
>>
>>1. In a function with *error* as an output (anywhere): returns in 
>>case the *err* declared with *watch err* (or *watch myerror*) becomes 
>>non-nil. *watch err* would declare *err*" as *var* does. Most use 
>>cases would put *watch err* at the beginning of a function (although 
>>this is optional as it is with *defer*)
>>2. In a test function; aka TestSomething(something *testing.T), *watch 
>>err error* would declare *err* (or *watch myerror error*) and if an 
>>error occurs, it would call something.FailNow() after (printing the error 
>>message?---still need to think this part better)
>>3. In the main function: *watch err error* would print the error 
>>message (or maybe pipe to stderr) and os.Exist(1)
>>4. *watchif err != nil {HERE}* would be more powerful because it 
>>would allow us to do other things. But the mechanism is similar (as you 
>>proposed initially): if *err* becomes non-nil anywhere, the execution 
>>in *HERE* would take place.
>>
>> Cheers!
>>
>>
>> On Tuesday, September 5, 2017 at 4:55:59 PM UTC+10, 
>> marti...@programmfabrik.de wrote:
>>>
>>> Hi Dorival,
>>>
>>> thanks for supporting me with my idea.
>>>
>>> And yes, after writing my post yesterday I was thinking, "watchif" or 
>>> even simply "watch".
>>>
>>> And yes, today I am more in favor of simply *"watch"*.
>>>
>>> And yes, we can constrain this to the context of one function (like 
>>> defer), I am ok with that. 
>>>
>>> What you are describing how you work with errors and how you spent hours 
>>> adding 
>>>
>>> *if err != nil*
>>>
>>> that is *exactly* my point.
>>>
>>> On could nicely write this
>>>
>>> ...
>>> watch err!=nil {
>>>   handle_sql_error(err)
>>> }
>>> ...
>>>
>>> Of course, watch could also be used to not watch out for errors but any 
>>> other places where new values to get assigned to variables.
>>>
>>> Martin
>>>
>>>>
>>>>>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [go-nuts] error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
Martin, Certainly!
I have (in https://github.com/cpmech/gosl):
Total number of files = 430
Total number of lines = 73470
(NOTE: there are Go (30%), C (30%), C++ (16%), and Fortran (8%), plus 
Python and R files in there...)

On Tuesday, September 5, 2017 at 5:24:28 PM UTC+10, 
marti...@programmfabrik.de wrote:
>
> Dorival,
>
> thanks for counting your error calls, but without any other number showing 
> the size of your project they cannot really put in perspective ;-)
>
> And I think *watch* should not only be function bound, but bound to the 
> current scope, same as *var*.
>
> Martin
>
>
> On Tuesday, September 5, 2017 at 9:20:10 AM UTC+2, Dorival Pedroso wrote:
>>
>> And I've written 231 error messages (I use a function called chk.Err() to 
>> do so):
>> find . -iname "*.go" -exec grep -inH "chk.Err" {} \; | wc -l
>> 231
>>
>> See the messages here: 
>> https://gist.github.com/cpmech/d2e36dcbe277cd72605f3732d79c798b 
>>
>> And I have a feeling that I've done only 20% of the error messages... 
>> (lots of work still needed...)
>>
>>
>> On Tuesday, September 5, 2017 at 5:15:16 PM UTC+10, Dorival Pedroso wrote:
>>>
>>> I'm working on a Go project right now and I realised I've written 569 
>>> "if err != nil":
>>> find . -iname "*.go" -exec grep -inH "if err != nil" {} \; | wc -l
>>> 569
>>>
>>>
>>> On Tuesday, September 5, 2017 at 4:57:45 PM UTC+10, Axel Wagner wrote:
>>>>
>>>>
>>>>
>>>> On Tue, Sep 5, 2017 at 8:49 AM, <marti...@programmfabrik.de> wrote:
>>>>
>>>>> Axel, 
>>>>>
>>>>> thanks for the reply.
>>>>>
>>>>> As I already replied to Tomas, I am not looking for improvements in 
>>>>> this particular case where I need to call an SQL database.
>>>>>
>>>>> An no, I dont want to wrap all function I use into something which 
>>>>> collects the errors for me.
>>>>>
>>>>> Let's say you want to log & panic & exit after any error.
>>>>>
>>>>> How do you do that, without putting code after each statement or 
>>>>> wrapping?
>>>>>
>>>>
>>>> You don't. But it's a bad idea. And "I want to make writing bad code 
>>>> easier" isn't a very convincing argument for a language-change.
>>>>
>>>> You can't. And that's why I am proposing to be a little bit open to new 
>>>>> ideas.
>>>>>
>>>>
>>>> And how open are you to the idea that good error handling isn't about 
>>>> writing the least amount of code or bubbling up an error in the most 
>>>> efficient way, but about *handling errors*? Because you haven't really 
>>>> replied to that part.
>>>>
>>>> (and FTR, one of the points I was making is, that this isn't a new 
>>>> idea. It's proposed fairly frequently)
>>>>  
>>>>
>>>>> Every modern language I know of has some sort of try...catch construct.
>>>>>
>>>>
>>>> Go is modern and doesn't have it. So this seems cherry-picked.
>>>>  
>>>>
>>>>>
>>>>>
>>>>> Martin
>>>>>
>>>>>
>>>>>
>>>>>
>>>>> On Monday, September 4, 2017 at 10:57:51 PM UTC+2, Axel Wagner wrote:
>>>>>>
>>>>>> See, e.g. here 
>>>>>> <https://groups.google.com/d/topic/golang-nuts/ROr5jveMQvg/discussion> 
>>>>>> or 
>>>>>> here 
>>>>>> <https://groups.google.com/d/topic/golang-nuts/68J-mLCC1JI/discussion> 
>>>>>> for 
>>>>>> previous discussions of very similar (even mostly identical) proposals.
>>>>>>
>>>>>> What I always dislike about these kinds of proposals is, that they 
>>>>>> are encouraging not handling errors, but instead just passing them 
>>>>>> up-stack. In general, all of the sites where you are checking for errors 
>>>>>> will signify different error conditions, that should be communicated 
>>>>>> differently upstream. For example:
>>>>>>
>>>>>> db.Prepare("INSERT INTO userinfo(username, departname, created) 
>>>>>> values(?,?,?)")
>>>>>> -> This

[go-nuts] Re: error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
Hi Martin;

What about two commands "*watch*" and "*watchif*"?

The first works as the "*var*" command and the second as the "*if*" command.

"*watch*" does:

   1. In a function with *error* as an output (anywhere): returns in case 
   the *err* declared with *watch err* (or *watch myerror*) becomes 
   non-nil. *watch err* would declare *err*" as *var* does. Most use cases 
   would put *watch err* at the beginning of a function (although this is 
   optional as it is with *defer*)
   2. In a test function; aka TestSomething(something *testing.T), *watch 
   err error* would declare *err* (or *watch myerror error*) and if an 
   error occurs, it would call something.FailNow() after (printing the error 
   message?---still need to think this part better)
   3. In the main function: *watch err error* would print the error message 
   (or maybe pipe to stderr) and os.Exist(1)
   4. *watchif err != nil {HERE}* would be more powerful because it would 
   allow us to do other things. But the mechanism is similar (as you proposed 
   initially): if *err* becomes non-nil anywhere, the execution in *HERE* 
   would take place.

Cheers!


On Tuesday, September 5, 2017 at 4:55:59 PM UTC+10, 
marti...@programmfabrik.de wrote:
>
> Hi Dorival,
>
> thanks for supporting me with my idea.
>
> And yes, after writing my post yesterday I was thinking, "watchif" or even 
> simply "watch".
>
> And yes, today I am more in favor of simply *"watch"*.
>
> And yes, we can constrain this to the context of one function (like 
> defer), I am ok with that. 
>
> What you are describing how you work with errors and how you spent hours 
> adding 
>
> *if err != nil*
>
> that is *exactly* my point.
>
> On could nicely write this
>
> ...
> watch err!=nil {
>   handle_sql_error(err)
> }
> ...
>
> Of course, watch could also be used to not watch out for errors but any 
> other places where new values to get assigned to variables.
>
> Martin
>
>>
>>>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [go-nuts] error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
And I've written 231 error messages (I use a function called chk.Err() to 
do so):
find . -iname "*.go" -exec grep -inH "chk.Err" {} \; | wc -l
231

See the messages 
here: https://gist.github.com/cpmech/d2e36dcbe277cd72605f3732d79c798b 

And I have a feeling that I've done only 20% of the error messages... (lots 
of work still needed...)


On Tuesday, September 5, 2017 at 5:15:16 PM UTC+10, Dorival Pedroso wrote:
>
> I'm working on a Go project right now and I realised I've written 569 "if 
> err != nil":
> find . -iname "*.go" -exec grep -inH "if err != nil" {} \; | wc -l
> 569
>
>
> On Tuesday, September 5, 2017 at 4:57:45 PM UTC+10, Axel Wagner wrote:
>>
>>
>>
>> On Tue, Sep 5, 2017 at 8:49 AM, <marti...@programmfabrik.de> wrote:
>>
>>> Axel, 
>>>
>>> thanks for the reply.
>>>
>>> As I already replied to Tomas, I am not looking for improvements in this 
>>> particular case where I need to call an SQL database.
>>>
>>> An no, I dont want to wrap all function I use into something which 
>>> collects the errors for me.
>>>
>>> Let's say you want to log & panic & exit after any error.
>>>
>>> How do you do that, without putting code after each statement or 
>>> wrapping?
>>>
>>
>> You don't. But it's a bad idea. And "I want to make writing bad code 
>> easier" isn't a very convincing argument for a language-change.
>>
>> You can't. And that's why I am proposing to be a little bit open to new 
>>> ideas.
>>>
>>
>> And how open are you to the idea that good error handling isn't about 
>> writing the least amount of code or bubbling up an error in the most 
>> efficient way, but about *handling errors*? Because you haven't really 
>> replied to that part.
>>
>> (and FTR, one of the points I was making is, that this isn't a new idea. 
>> It's proposed fairly frequently)
>>  
>>
>>> Every modern language I know of has some sort of try...catch construct.
>>>
>>
>> Go is modern and doesn't have it. So this seems cherry-picked.
>>  
>>
>>>
>>>
>>> Martin
>>>
>>>
>>>
>>>
>>> On Monday, September 4, 2017 at 10:57:51 PM UTC+2, Axel Wagner wrote:
>>>>
>>>> See, e.g. here 
>>>> <https://groups.google.com/d/topic/golang-nuts/ROr5jveMQvg/discussion> or 
>>>> here 
>>>> <https://groups.google.com/d/topic/golang-nuts/68J-mLCC1JI/discussion> for 
>>>> previous discussions of very similar (even mostly identical) proposals.
>>>>
>>>> What I always dislike about these kinds of proposals is, that they are 
>>>> encouraging not handling errors, but instead just passing them up-stack. 
>>>> In 
>>>> general, all of the sites where you are checking for errors will signify 
>>>> different error conditions, that should be communicated differently 
>>>> upstream. For example:
>>>>
>>>> db.Prepare("INSERT INTO userinfo(username, departname, created) 
>>>> values(?,?,?)")
>>>> -> This could fail for basically two reasons: Either communication with 
>>>> your database somehow failed (e.g. a broken network connection), in which 
>>>> case you want to return the equivalent of an HTTP 503 error, or the syntax 
>>>> of your statement is wrong, in which case I'd argue panic'ing would be the 
>>>> correct thing - at the very least, returning the equivalent of a 500.
>>>>
>>>> stmt.Exec("astaxie", "研发部门", "2012-12-09")
>>>> -> Either a 503. Or 400, 403, 409…
>>>>
>>>> res.LastInsertId()
>>>> -> 500 or 501?
>>>>
>>>> The issue is, that by simply checking for nil and passing it along, you 
>>>> are *not handling your error*. Different error conditions require 
>>>> different 
>>>> error handling and what the correct error handling is, depends heavily on 
>>>> the application. An ENODIR error in one line of code can signify a totally 
>>>> different error condition than the same error two lines later. So all of 
>>>> these proposals are born out of an exception-style idea of how error 
>>>> handling is supposed to work; deep within the call stack something goes 
>>>> wrong and that something is then just bubbled up to be someone else's 
>>>> problem. Good err

Re: [go-nuts] error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
I'm working on a Go project right now and I realised I've written 569 "if 
err != nil":
find . -iname "*.go" -exec grep -inH "if err != nil" {} \; | wc -l
569


On Tuesday, September 5, 2017 at 4:57:45 PM UTC+10, Axel Wagner wrote:
>
>
>
> On Tue, Sep 5, 2017 at 8:49 AM,  
> wrote:
>
>> Axel, 
>>
>> thanks for the reply.
>>
>> As I already replied to Tomas, I am not looking for improvements in this 
>> particular case where I need to call an SQL database.
>>
>> An no, I dont want to wrap all function I use into something which 
>> collects the errors for me.
>>
>> Let's say you want to log & panic & exit after any error.
>>
>> How do you do that, without putting code after each statement or wrapping?
>>
>
> You don't. But it's a bad idea. And "I want to make writing bad code 
> easier" isn't a very convincing argument for a language-change.
>
> You can't. And that's why I am proposing to be a little bit open to new 
>> ideas.
>>
>
> And how open are you to the idea that good error handling isn't about 
> writing the least amount of code or bubbling up an error in the most 
> efficient way, but about *handling errors*? Because you haven't really 
> replied to that part.
>
> (and FTR, one of the points I was making is, that this isn't a new idea. 
> It's proposed fairly frequently)
>  
>
>> Every modern language I know of has some sort of try...catch construct.
>>
>
> Go is modern and doesn't have it. So this seems cherry-picked.
>  
>
>>
>>
>> Martin
>>
>>
>>
>>
>> On Monday, September 4, 2017 at 10:57:51 PM UTC+2, Axel Wagner wrote:
>>>
>>> See, e.g. here 
>>>  or 
>>> here 
>>>  for 
>>> previous discussions of very similar (even mostly identical) proposals.
>>>
>>> What I always dislike about these kinds of proposals is, that they are 
>>> encouraging not handling errors, but instead just passing them up-stack. In 
>>> general, all of the sites where you are checking for errors will signify 
>>> different error conditions, that should be communicated differently 
>>> upstream. For example:
>>>
>>> db.Prepare("INSERT INTO userinfo(username, departname, created) 
>>> values(?,?,?)")
>>> -> This could fail for basically two reasons: Either communication with 
>>> your database somehow failed (e.g. a broken network connection), in which 
>>> case you want to return the equivalent of an HTTP 503 error, or the syntax 
>>> of your statement is wrong, in which case I'd argue panic'ing would be the 
>>> correct thing - at the very least, returning the equivalent of a 500.
>>>
>>> stmt.Exec("astaxie", "研发部门", "2012-12-09")
>>> -> Either a 503. Or 400, 403, 409…
>>>
>>> res.LastInsertId()
>>> -> 500 or 501?
>>>
>>> The issue is, that by simply checking for nil and passing it along, you 
>>> are *not handling your error*. Different error conditions require different 
>>> error handling and what the correct error handling is, depends heavily on 
>>> the application. An ENODIR error in one line of code can signify a totally 
>>> different error condition than the same error two lines later. So all of 
>>> these proposals are born out of an exception-style idea of how error 
>>> handling is supposed to work; deep within the call stack something goes 
>>> wrong and that something is then just bubbled up to be someone else's 
>>> problem. Good error handling just can't be well abbreviated in this way - 
>>> at least not generically. It's too application-specific for that.
>>>
>>> On Mon, Sep 4, 2017 at 8:27 PM,  wrote:
>>>
 Seriously? And yes, I have read 
 https://blog.golang.org/errors-are-values...

 The best case reduction I found is:

 ...
 res, err = stmt.Exec("astaxieupdate", id)
 checkError(err)
 ...

 Still, I need this after each line of calling a function which may 
 return an error.

>>>
>>> A better take-away from that blog post would have been, to orient 
>>> yourself around the example of a writer given. You could, for example, 
>>> provide a one-time abstraction that wraps *sql.DB and collects the error. 
>>> I'd agree that the sql package tends to not be amazing for that, because of 
>>> its set of interdependent types, it is still possible. For example, with 
>>> this , you could write
>>>
>>> d := {db: d}
>>> stmt := d.Prepare("INSERT INTO…")
>>> res := stmt.Exec(…)
>>> id := res.LastInsertId()
>>> stmt := d.Prepare("UPDATE…")
>>> res := stmt.Exec(…, id)
>>> affect := res.RowsAffected()
>>> return d.err
>>>
>>> Now… this isn't really nice either (see above. sql isn't really 
>>> well-designed for this. You'd probably try and implement a driver for this, 
>>> but sql doesn't make that easy either). And it's a bad idea for all the 
>>> same reasons the watch-proposal isn't a great idea here. But it illustrates 
>>> a far 

Re: [go-nuts] error handling needs syntactical sugar

2017-09-05 Thread Dorival Pedroso
Hi Axel, thanks for your input.

I think Martin's proposal is all right.

We'll certainly keep suggesting all good practices to handle errors (I 
myself have tons of error messages + handling..).

Go is perfect in doing this. We can even mimic "try" + "catch" with "panic" 
+ "recover" (although I rarely use these nowadays).

The proposal is not a language change at all! It's a new command to do what 
we've discussed earlier. It's perfectly backward compatible and by no means 
replace any existent technique for error handling!

Cheers.
Dorival

On Tuesday, September 5, 2017 at 4:57:45 PM UTC+10, Axel Wagner wrote:
>
>
>
> On Tue, Sep 5, 2017 at 8:49 AM,  
> wrote:
>
>> Axel, 
>>
>> thanks for the reply.
>>
>> As I already replied to Tomas, I am not looking for improvements in this 
>> particular case where I need to call an SQL database.
>>
>> An no, I dont want to wrap all function I use into something which 
>> collects the errors for me.
>>
>> Let's say you want to log & panic & exit after any error.
>>
>> How do you do that, without putting code after each statement or wrapping?
>>
>
> You don't. But it's a bad idea. And "I want to make writing bad code 
> easier" isn't a very convincing argument for a language-change.
>
> You can't. And that's why I am proposing to be a little bit open to new 
>> ideas.
>>
>
> And how open are you to the idea that good error handling isn't about 
> writing the least amount of code or bubbling up an error in the most 
> efficient way, but about *handling errors*? Because you haven't really 
> replied to that part.
>
> (and FTR, one of the points I was making is, that this isn't a new idea. 
> It's proposed fairly frequently)
>  
>
>> Every modern language I know of has some sort of try...catch construct.
>>
>
> Go is modern and doesn't have it. So this seems cherry-picked.
>  
>
>>
>>
>> Martin
>>
>>
>>
>>
>> On Monday, September 4, 2017 at 10:57:51 PM UTC+2, Axel Wagner wrote:
>>>
>>> See, e.g. here 
>>>  or 
>>> here 
>>>  for 
>>> previous discussions of very similar (even mostly identical) proposals.
>>>
>>> What I always dislike about these kinds of proposals is, that they are 
>>> encouraging not handling errors, but instead just passing them up-stack. In 
>>> general, all of the sites where you are checking for errors will signify 
>>> different error conditions, that should be communicated differently 
>>> upstream. For example:
>>>
>>> db.Prepare("INSERT INTO userinfo(username, departname, created) 
>>> values(?,?,?)")
>>> -> This could fail for basically two reasons: Either communication with 
>>> your database somehow failed (e.g. a broken network connection), in which 
>>> case you want to return the equivalent of an HTTP 503 error, or the syntax 
>>> of your statement is wrong, in which case I'd argue panic'ing would be the 
>>> correct thing - at the very least, returning the equivalent of a 500.
>>>
>>> stmt.Exec("astaxie", "研发部门", "2012-12-09")
>>> -> Either a 503. Or 400, 403, 409…
>>>
>>> res.LastInsertId()
>>> -> 500 or 501?
>>>
>>> The issue is, that by simply checking for nil and passing it along, you 
>>> are *not handling your error*. Different error conditions require different 
>>> error handling and what the correct error handling is, depends heavily on 
>>> the application. An ENODIR error in one line of code can signify a totally 
>>> different error condition than the same error two lines later. So all of 
>>> these proposals are born out of an exception-style idea of how error 
>>> handling is supposed to work; deep within the call stack something goes 
>>> wrong and that something is then just bubbled up to be someone else's 
>>> problem. Good error handling just can't be well abbreviated in this way - 
>>> at least not generically. It's too application-specific for that.
>>>
>>> On Mon, Sep 4, 2017 at 8:27 PM,  wrote:
>>>
 Seriously? And yes, I have read 
 https://blog.golang.org/errors-are-values...

 The best case reduction I found is:

 ...
 res, err = stmt.Exec("astaxieupdate", id)
 checkError(err)
 ...

 Still, I need this after each line of calling a function which may 
 return an error.

>>>
>>> A better take-away from that blog post would have been, to orient 
>>> yourself around the example of a writer given. You could, for example, 
>>> provide a one-time abstraction that wraps *sql.DB and collects the error. 
>>> I'd agree that the sql package tends to not be amazing for that, because of 
>>> its set of interdependent types, it is still possible. For example, with 
>>> this , you could write
>>>
>>> d := {db: d}
>>> stmt := d.Prepare("INSERT INTO…")
>>> res := stmt.Exec(…)
>>> id := res.LastInsertId()
>>> stmt := d.Prepare("UPDATE…")
>>> res := 

[go-nuts] Re: error handling needs syntactical sugar

2017-09-04 Thread Dorival Pedroso
I forgot (again) to say that in this case the error would just be returned. 

In other words, `watch err` would just check if `err != nil` and then 
return.

The other cases (test, main) would be as explained earlier (FailNow(), 
Exit(1))

On Tuesday, September 5, 2017 at 10:14:16 AM UTC+10, Dorival Pedroso wrote:
>
> Hi, the `watch err` could also work in "APIs" that already return "error".
>
> For instance:
> package myapi
>
> func First() (err error) {
> watch err
> err = internalFunction(1,2,3)
> err = internalFunction(3,2,1)
> err = internalFunction(1,3,2)
> }
>
>
>
>
> On Tuesday, September 5, 2017 at 4:27:20 AM UTC+10, 
> marti...@programmfabrik.de wrote:
>>
>> Hi guys,
>>
>> at first I though I really like the idea of how Go deals with error 
>> management and handling, but the more Go code I look at or try to program, 
>> the more I get scared about checking errors every second line in every 
>> given block of code.
>>
>> Take a look at this example here from "Build Web Application with Golang":
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) 
>> values(?,?,?)")
>> if err != nil {
>>   // handle error
>> }
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> if err != nil {
>>   // handle error
>> }
>> id, err := res.LastInsertId()
>> if err != nil {
>>   // handle error
>> }
>> fmt.Println(id)
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> if err != nil {
>>   // handle error
>> }
>> res, err = stmt.Exec("astaxieupdate", id)
>> if err != nil {
>>   // handle error
>> }
>> affect, err := res.RowsAffected()
>> if err != nil {
>>   // handle error
>> }
>>
>>
>> Seriously? And yes, I have read 
>> https://blog.golang.org/errors-are-values...
>>
>> The best case reduction I found is:
>>
>> ...
>> res, err = stmt.Exec("astaxieupdate", id)
>> checkError(err)
>> ...
>>
>> Still, I need this after each line of calling a function which may return 
>> an error.
>>
>> I bet this is not pleasant to do in larger code bases and it also takes 
>> away focus from what is actually happening.
>>
>> 50-80% of all lines of code in my example deal with error handling?
>>
>> This is not good. Seriously.
>>
>> And don't get me wrong, there is a lot of things I really like, love and 
>> adore about Go, but catching errors needs an improved syntax!
>>
>> And I am not proposing try...catch here. 
>>
>> How about introducing a new piece of syntax 
>>
>> "watch if   " 
>>
>> which tells the compiler to watch out for changes in a given SimpleStmt
>>
>> The same code as above would look like this:
>>
>> var err Error
>>
>> watch if err != nil {
>>   // handle error(s)
>> }
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, 
>> created) values(?,?,?)")
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> id, err := res.LastInsertId()
>> fmt.Println(id)
>>
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> res, err = stmt.Exec("astaxieupdate", id)
>> affect, err := res.RowsAffected()
>>
>>
>>- The "watch if" would be executed after each assignment of any of 
>>the variables used in SimpleStmt of the statement.
>>- Multiple "watch if" would be executed in order or appearance
>>- The "watch if" could be used like "defer..." inside functions
>>- The "watch if" would work in its full scope of the watched variables
>>
>> I am not a language expert, so may be there is a saner way of expression 
>> what I want to achieve.
>>
>> But bottom line is, there should by an easier to read and write way to 
>> deal with errors in Go.
>>
>>
>> Martin
>>
>>
>>
>>
>>
>>

-- 
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: error handling needs syntactical sugar

2017-09-04 Thread Dorival Pedroso
Hi, the `watch err` could also work in "APIs" that already return "error".

For instance:
package myapi

func First() (err error) {
watch err
err = internalFunction(1,2,3)
err = internalFunction(3,2,1)
err = internalFunction(1,3,2)
}




On Tuesday, September 5, 2017 at 4:27:20 AM UTC+10, 
marti...@programmfabrik.de wrote:
>
> Hi guys,
>
> at first I though I really like the idea of how Go deals with error 
> management and handling, but the more Go code I look at or try to program, 
> the more I get scared about checking errors every second line in every 
> given block of code.
>
> Take a look at this example here from "Build Web Application with Golang":
>
> // insert
> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) 
> values(?,?,?)")
> if err != nil {
>   // handle error
> }
> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
> if err != nil {
>   // handle error
> }
> id, err := res.LastInsertId()
> if err != nil {
>   // handle error
> }
> fmt.Println(id)
> // update
> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
> if err != nil {
>   // handle error
> }
> res, err = stmt.Exec("astaxieupdate", id)
> if err != nil {
>   // handle error
> }
> affect, err := res.RowsAffected()
> if err != nil {
>   // handle error
> }
>
>
> Seriously? And yes, I have read https://blog.golang.org/errors-are-values.
> ..
>
> The best case reduction I found is:
>
> ...
> res, err = stmt.Exec("astaxieupdate", id)
> checkError(err)
> ...
>
> Still, I need this after each line of calling a function which may return 
> an error.
>
> I bet this is not pleasant to do in larger code bases and it also takes 
> away focus from what is actually happening.
>
> 50-80% of all lines of code in my example deal with error handling?
>
> This is not good. Seriously.
>
> And don't get me wrong, there is a lot of things I really like, love and 
> adore about Go, but catching errors needs an improved syntax!
>
> And I am not proposing try...catch here. 
>
> How about introducing a new piece of syntax 
>
> "watch if   " 
>
> which tells the compiler to watch out for changes in a given SimpleStmt
>
> The same code as above would look like this:
>
> var err Error
>
> watch if err != nil {
>   // handle error(s)
> }
>
> // insert
> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, 
> created) values(?,?,?)")
> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
> id, err := res.LastInsertId()
> fmt.Println(id)
>
> // update
> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
> res, err = stmt.Exec("astaxieupdate", id)
> affect, err := res.RowsAffected()
>
>
>- The "watch if" would be executed after each assignment of any of the 
>variables used in SimpleStmt of the statement.
>- Multiple "watch if" would be executed in order or appearance
>- The "watch if" could be used like "defer..." inside functions
>- The "watch if" would work in its full scope of the watched variables
>
> I am not a language expert, so may be there is a saner way of expression 
> what I want to achieve.
>
> But bottom line is, there should by an easier to read and write way to 
> deal with errors in Go.
>
>
> Martin
>
>
>
>
>
>

-- 
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: error handling needs syntactical sugar

2017-09-04 Thread Dorival Pedroso
by the way, above, I was thinking of `watch` as a counterpart of `var`...

On Tuesday, September 5, 2017 at 8:56:24 AM UTC+10, Dorival Pedroso wrote:
>
> Hi,
>
> Error management in Go is perfect!
>
> But I like the idea of `watch` (may we drop the `if`?)
>
> So, `watch` would work in the context of a function like `defer`. However, 
> this would effectively become a `catcher` for errors (instead of `panics`) 
> within the `defer` function, right?
>
> Also, I think `watch` would effectively be a "conditioned defer".
>
> Once, I've spent hours adding `if err != nil { ... }` elsewhere in my 
> code. Lately, I've started using two auxiliary functions just for 
> readability:
>
> In tests, I use:
> func status(tst *testing.T, err error) {
> if err != nil {
> tst.Errorf("ERROR: %v\n", err)
> tst.FailNow()
> }
> }
>
> func TestBessel01(tst *testing.T) {
> dat, err := ReadTable("data/as-9-bessel-integer-big.cmp")
> status(tst, err)
> ...
> }
>
> In "main functions", I use:
> func status(err error) {
> if err != nil {
> io.Pf("ERROR: %v\n", err)
> os.Exit(1)
> }
> }
>
> I (try to) check the errors everywhere in the API and these "syntax 
> sugars" are only required at the final stages ("test mode" or "main 
> function").
>
> So, `watch` could be something like:
> func TestBessel01(tst *testing.T) {
> watch err error // the compiler could detect that we're on "test" mode 
> and then return when err != nil
> dat, err := ReadTable("data/as-9-bessel-integer-big.cmp")
> err = ComputeWithData(dat)
> ...
> err = DoSomethingElse(dat)
> ...
> }
>
> In "main functions":
> func main() {
> watch err error // the compiler would detect that we're on "main 
> function" mode and then Exit(1)
> err := ComputeWithData(...)
> }
>
> The command `watch` could even be used for different purposes; e.g. when 
> something that should be  isn't.
>
> Cheers.
> D
>
>
> On Tuesday, September 5, 2017 at 4:27:20 AM UTC+10, 
> marti...@programmfabrik.de wrote:
>>
>> Hi guys,
>>
>> at first I though I really like the idea of how Go deals with error 
>> management and handling, but the more Go code I look at or try to program, 
>> the more I get scared about checking errors every second line in every 
>> given block of code.
>>
>> Take a look at this example here from "Build Web Application with Golang":
>>
>> // insert
>> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) 
>> values(?,?,?)")
>> if err != nil {
>>   // handle error
>> }
>> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
>> if err != nil {
>>   // handle error
>> }
>> id, err := res.LastInsertId()
>> if err != nil {
>>   // handle error
>> }
>> fmt.Println(id)
>> // update
>> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>> if err != nil {
>>   // handle error
>> }
>> res, err = stmt.Exec("astaxieupdate", id)
>> if err != nil {
>>   // handle error
>> }
>> affect, err := res.RowsAffected()
>> if err != nil {
>>   // handle error
>> }
>>
>>
>> Seriously? And yes, I have read 
>> https://blog.golang.org/errors-are-values...
>>
>> The best case reduction I found is:
>>
>> ...
>> res, err = stmt.Exec("astaxieupdate", id)
>> checkError(err)
>> ...
>>
>> Still, I need this after each line of calling a function which may return 
>> an error.
>>
>> I bet this is not pleasant to do in larger code bases and it also takes 
>> away focus from what is actually happening.
>>
>> 50-80% of all lines of code in my example deal with error handling?
>>
>> This is not good. Seriously.
>>
>> And don't get me wrong, there is a lot of things I really like, love and 
>> adore about Go, but catching errors needs an improved syntax!
>>
>> And I am not proposing try...catch here. 
>>
>> How about introducing a new piece of syntax 
>>
>> "watch if   " 
>>
>> which tells the compiler to watch out for changes in a given SimpleStmt
>>
>> The same code as above would look like this:
>>
>> var err Error
>>
>> watch if err != nil {
>>   // handle error(s)
>> }
>>
>> // insert

[go-nuts] Re: error handling needs syntactical sugar

2017-09-04 Thread Dorival Pedroso
Hi,

Error management in Go is perfect!

But I like the idea of `watch` (may we drop the `if`?)

So, `watch` would work in the context of a function like `defer`. However, 
this would effectively become a `catcher` for errors (instead of `panics`) 
within the `defer` function, right?

Also, I think `watch` would effectively be a "conditioned defer".

Once, I've spent hours adding `if err != nil { ... }` elsewhere in my code. 
Lately, I've started using two auxiliary functions just for readability:

In tests, I use:
func status(tst *testing.T, err error) {
if err != nil {
tst.Errorf("ERROR: %v\n", err)
tst.FailNow()
}
}

func TestBessel01(tst *testing.T) {
dat, err := ReadTable("data/as-9-bessel-integer-big.cmp")
status(tst, err)
...
}

In "main functions", I use:
func status(err error) {
if err != nil {
io.Pf("ERROR: %v\n", err)
os.Exit(1)
}
}

I (try to) check the errors everywhere in the API and these "syntax sugars" 
are only required at the final stages ("test mode" or "main function").

So, `watch` could be something like:
func TestBessel01(tst *testing.T) {
watch err error // the compiler could detect that we're on "test" mode 
and then return when err != nil
dat, err := ReadTable("data/as-9-bessel-integer-big.cmp")
err = ComputeWithData(dat)
...
err = DoSomethingElse(dat)
...
}

In "main functions":
func main() {
watch err error // the compiler would detect that we're on "main 
function" mode and then Exit(1)
err := ComputeWithData(...)
}

The command `watch` could even be used for different purposes; e.g. when 
something that should be  isn't.

Cheers.
D


On Tuesday, September 5, 2017 at 4:27:20 AM UTC+10, 
marti...@programmfabrik.de wrote:
>
> Hi guys,
>
> at first I though I really like the idea of how Go deals with error 
> management and handling, but the more Go code I look at or try to program, 
> the more I get scared about checking errors every second line in every 
> given block of code.
>
> Take a look at this example here from "Build Web Application with Golang":
>
> // insert
> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) 
> values(?,?,?)")
> if err != nil {
>   // handle error
> }
> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
> if err != nil {
>   // handle error
> }
> id, err := res.LastInsertId()
> if err != nil {
>   // handle error
> }
> fmt.Println(id)
> // update
> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
> if err != nil {
>   // handle error
> }
> res, err = stmt.Exec("astaxieupdate", id)
> if err != nil {
>   // handle error
> }
> affect, err := res.RowsAffected()
> if err != nil {
>   // handle error
> }
>
>
> Seriously? And yes, I have read https://blog.golang.org/errors-are-values.
> ..
>
> The best case reduction I found is:
>
> ...
> res, err = stmt.Exec("astaxieupdate", id)
> checkError(err)
> ...
>
> Still, I need this after each line of calling a function which may return 
> an error.
>
> I bet this is not pleasant to do in larger code bases and it also takes 
> away focus from what is actually happening.
>
> 50-80% of all lines of code in my example deal with error handling?
>
> This is not good. Seriously.
>
> And don't get me wrong, there is a lot of things I really like, love and 
> adore about Go, but catching errors needs an improved syntax!
>
> And I am not proposing try...catch here. 
>
> How about introducing a new piece of syntax 
>
> "watch if   " 
>
> which tells the compiler to watch out for changes in a given SimpleStmt
>
> The same code as above would look like this:
>
> var err Error
>
> watch if err != nil {
>   // handle error(s)
> }
>
> // insert
> stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, 
> created) values(?,?,?)")
> res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
> id, err := res.LastInsertId()
> fmt.Println(id)
>
> // update
> stmt, err = db.Prepare("update userinfo set username=? where uid=?")
> res, err = stmt.Exec("astaxieupdate", id)
> affect, err := res.RowsAffected()
>
>
>- The "watch if" would be executed after each assignment of any of the 
>variables used in SimpleStmt of the statement.
>- Multiple "watch if" would be executed in order or appearance
>- The "watch if" could be used like "defer..." inside functions
>- The "watch if" would work in its full scope of the watched variables
>
> I am not a language expert, so may be there is a saner way of expression 
> what I want to achieve.
>
> But bottom line is, there should by an easier to read and write way to 
> deal with errors in Go.
>
>
> Martin
>
>
>
>
>
>

-- 
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: How to optimize as with -O2 from Gcc? (50x speedup)

2017-08-06 Thread Dorival Pedroso
Fixed. Cheers.

On Sunday, August 6, 2017 at 12:23:57 PM UTC+10, Michael Jones wrote:
>
> Great. Hope it helps. I had a typo in power 0 (which is never called. 
> Change the return to 1.0.
>
> On Sat, Aug 5, 2017 at 6:50 PM  wrote:
>
>> Thanks, Michael.
>>
>> I've created a tiny project with those files here: 
>> https://github.com/cpmech/go-fast-math-experiments
>>
>> The output of go test -run=XXX -bench=. -benchtime=10s (in the xmath 
>> package) is:
>> BenchmarkPowStd-32   349.8 ns/op
>> BenchmarkPowP-32 20 8.85 ns/op
>> BenchmarkPowFI-32 20 6.31 ns/op
>> BenchmarkPowStd10-32 1   237 ns/op
>> BenchmarkPowP10-32   539.1 ns/op
>> BenchmarkPowFI10-32   344.6 ns/op
>> BenchmarkPowStd20-32 3000   549 ns/op
>> BenchmarkPowP20-32   297.4 ns/op
>> BenchmarkPowFI20-32   293.8 ns/op
>> BenchmarkPowStd50-32 1000  1584 ns/op
>> BenchmarkPowP50-32   5000   304 ns/op
>> BenchmarkPowFI50-32   5000   249 ns/op
>> BenchmarkPowStd100-32 500  3529 ns/op
>> BenchmarkPowP100-32   2000   692 ns/op
>> BenchmarkPowFI100-32 3000   522 ns/op
>> BenchmarkPowStd200-32 200  9221 ns/op
>> BenchmarkPowP200-32   1000  1623 ns/op
>> BenchmarkPowFI200-32 2000  1124 ns/op
>>
>> Your table-based function (PowFI) wins overall with ~7x speedup vs mine 
>> (PowP) with ~5x speedup (compared to the std math which is 
>> non-integer-specific, so, not very fair... but OK as reference).
>>
>> Cheers.
>> Dorival
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to golang-nuts...@googlegroups.com .
>> For more options, visit https://groups.google.com/d/optout.
>>
> -- 
> Michael T. Jones
> michae...@gmail.com 
>

-- 
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: Concurrency Testimonial

2017-08-06 Thread Dorival Pedroso
Great news. Thanks for sharing

On Sunday, August 6, 2017 at 1:37:11 AM UTC+10, Mandolyte wrote:
>
> This past week I wrote an "audit" program for management to see how a long 
> running data migration effort was going (it will take several months to 
> complete). I was little discouraged when I found that the audit was on pace 
> to complete in 10 days. That got me to thinking of making a concurrent 
> version of the code. It's been over a year since I last did anything with 
> channels, so I spent some time studying my previous examples, did some 
> google searches, etc.
>
> In just a few hours I had it converted, only had a single deadlock bug to 
> figure out. Found that it was very easy to reason about. I made it so it 
> could use an argument specified number of go routines. With 10 concurrent 
> go routines, it is on pace to complete in less than 32 hours.
>
> So just a big thank you for such a nice language!
>

-- 
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 optimize as with -O2 from Gcc? (50x speedup)

2017-08-04 Thread Dorival Pedroso
I've noticed that this C code:

#include "math.h"
int main() {
double x = 2.5;
int Nmax = 1000;
for (int N=0; N

[go-nuts] Re: Generics are overrated.

2017-08-03 Thread Dorival Pedroso
Agreed!

And I was a "heavy" user of templates (see e.g. http://mechsys.nongnu.org/, 
including extensive use of "expression templates") ~5 years ago before the 
"wonders of Go".

Let's focus on making Go faster instead!

Cheers.
Dorival

On Friday, July 28, 2017 at 10:41:10 PM UTC+10, dogan...@dodobyte.com wrote:
>
> *Everything in this thread is my personal opinions, they are not 
> necessarily the truth.*
>
> My main language was C for a decade. I also liked Python. When i started 
> learning Go, it almost felt like i knew the language in another life. 
> Everything was so obvious.
>
> CSP model of concurrency was new to me though. Interfaces were more 
> familiar due to unix's open,close,read,write interface, which is the 
> greatest idea.
>
> I didn't use generics or templates much (it's kind of stupid for me to 
> talk about it's necessity), therefore this is more like a meta-research.
>
> - Go developers created a great standard library and many great software 
> without generics in the language.
> - Many companies switched to Go from the languages that have generics in 
> it.
> - A little copying is better than having a big feature in the language.
> - Using generics everywhere is more of a design choice than a necessity.
>
>
> *A language that doesn’t have everything is actually easier to program in 
> than some that do. (Dennis Ritchie).*
>
> I wrote many different types of software in C. A country wide (a big one) 
> server, two AV engines for two major AV companies etc. I needed generics 
> only few times, but i could handle it in C without using smart tricks. In 
> Go however, there are much safer, better and elegant solutions to achieve 
> the same results. Do we really need a big feature for it?
>
> I didn't hear a complaint about the lack of generics in Go from a C 
> programmer, although i'm sure there are. 
> Maybe java programmers use generics more than they are supposed to. Maybe 
> they should stop writing java in Go. I am confident that they would abuse 
> generics if Go had one.
>
> That brings me to my point.
>
> I believe that generics would divide the Go community.
>
> It's well known that everybody uses a subset of C++ language. Google 
> doesn't use exceptions for instance(afaik). I was unfortunate enough to use 
> C++ in my last company and i felt the pain.
>
> Rob Pike himself talked about it. 
> https://talks.golang.org/2012/splash.article (see 4. Pain points)
>
> Now Go is unique because people come to Go from all kind of different 
> languages, (javascript, Python, C,...). see 
> https://blog.golang.org/survey2016-results
>
> If Go 2 has a new fundamental feature like generics, many Go 2 programs 
> will look alien to Go 1 programmers. Some people will not use generics at 
> all while others overuse it.
>
> For a language like Go, this is disastrous because it's against Go's 
> philosophy. I love gofmt because it enforces a standart format and saves 
> our time of debating about indention and other things. What good it is to 
> have a standard format while you have completely different programming 
> styles.
>
> Dear Go experts;
>
> Please provide some best practices to achieve generic behavior for the 
> most common cases, instead of implementing Generics in Go.
>
> Let's end this debate and help keeping Go small and simple. It's the real 
> virtue of Go. 
>
> Thanks.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: Computations with complex numbers may be slow if care is not taken

2017-08-03 Thread Dorival Pedroso
This is the version of a pure imaginary real number raised to the power of 
n (integer):

// ImagXpowN computes (x⋅i)ⁿ
//
//   (x⋅i)¹ = x¹⋅i  (x⋅i)²  = -x²   (x⋅i)³  = -x³ ⋅i  (x⋅i)⁴  = 
x⁴
//   (x⋅i)⁵ = x⁵⋅i  (x⋅i)⁶  = -x⁶   (x⋅i)⁷  = -x⁷ ⋅i  (x⋅i)⁸  = 
x⁸
//   (x⋅i)⁹ = x⁹⋅i  (x⋅i)¹⁰ = -x¹⁰  (x⋅i)¹¹ = -x¹¹⋅i  (x⋅i)¹² = 
x¹²
//
func ImagXpowN(x float64, n int) complex128 {
if n == 0 {
return 1
}
xn := math.Pow(x, float64(n))
switch n % 4 {
case 1:
return complex(0, xn)
case 2:
return complex(-xn, 0)
case 3:
return complex(0, -xn)
}
return complex(xn, 0)
}


These are the benchmark functions:

func BenchmarkImagXpowN(b *testing.B) {
x := 2.5
for i := 0; i < b.N; i++ {
for n := 0; n < 200; n++ {
ImagXpowN(x, n)
}
}
}

func BenchmarkImagXpowNcmplx(b *testing.B) {
x := 2.5
for i := 0; i < b.N; i++ {
for n := 0; n < 200; n++ {
cmplx.Pow(complex(0, x), complex(float64(n), 0))
}
}
}


With the following results:
BenchmarkImagXpowN-32  20 10299 ns/op
BenchmarkImagXpowNcmplx-32  10 18595 ns/op

Now it's "just" 1.8x faster.

Cheers
D



On Friday, August 4, 2017 at 10:43:41 AM UTC+10, Dorival Pedroso wrote:
>
> Hi,
>
> This is an interesting benchmark:
>
> Given this function:
> // ImagPowN computes iⁿ = (√-1)ⁿ
> //
> //   i¹ = i  i²  = -1  i³  = -i  i⁴  = 1
> //   i⁵ = i  i⁶  = -1  i⁷  = -i  i⁸  = 1
> //   i⁹ = i  i¹⁰ = -1  i¹¹ = -i  i¹² = 1
> //
> func ImagPowN(n int) complex128 {
> if n == 0 {
> return 1
> }
> switch n % 4 {
> case 1:
> return 1i
> case 2:
> return -1
> case 3:
> return -1i
> }
> return 1
> }
>
> And this benchmark test:
> var (
> imagpownRes complex128
> )
>
> func BenchmarkImagPowN(b *testing.B) {
> var res complex128
> for i := 0; i < b.N; i++ {
> for n := 0; n < 200; n++ {
> res = ImagPowN(n)
> }
> }
> imagpownRes = res
> }
>
> func BenchmarkImagPowNcmplx(b *testing.B) {
> var res complex128
> for i := 0; i < b.N; i++ {
> for n := 0; n < 200; n++ {
> res = cmplx.Pow(1i, complex(float64(n), 0))
> }
> }
> imagpownRes = res
> }
>
> We get this output (  go test -run=XXX -bench=.  ):
> BenchmarkImagPowN-32 300   470 ns/op
> BenchmarkImagPowNcmplx-32  20 10050 ns/op
>
> A 20x speed up...
>
> Cheers.
> Dorival
>

-- 
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] Computations with complex numbers may be slow if care is not taken

2017-08-03 Thread Dorival Pedroso
Thanks for the advice.

This is the piece of code where I use that function:
// compute hat(Du)
pf := float64(p)
for j := 0; j < N; j++ {
ikp := ImagPowN(p) * complex(math.Pow(K[j], pf), 0)
DuHat[j] = ikp * S[j] * A[j]
}

where p is an integer (unbounded), K[j] is a real number from -Inf to +Inf 
and S[j] and A[j] are complex (unbounded too)

By using the ImagPowN(p) function, the code is much faster now...

Cheers.
D



On Friday, August 4, 2017 at 10:54:14 AM UTC+10, Michael Jones wrote:
>
> the complex power function is a difficult (time consuming) general 
> computation.
>
> are you saying that you actually have a program that uses boolean gaussian 
> integers and needs to do lots of power operations?
>
> if so, i highly recommend that you special case this for your own use. 
>
> if this is common then the power code could stop and check for Re(x) in 
> {-1,0,1} and Im(x) in {-1,0,1} before undertaking the general computation.
>
> On Thu, Aug 3, 2017 at 5:43 PM, Dorival Pedroso <dorival...@gmail.com 
> > wrote:
>
>> Hi,
>>
>> This is an interesting benchmark:
>>
>> Given this function:
>> // ImagPowN computes iⁿ = (√-1)ⁿ
>> //
>> //   i¹ = i  i²  = -1  i³  = -i  i⁴  = 1
>> //   i⁵ = i  i⁶  = -1  i⁷  = -i  i⁸  = 1
>> //   i⁹ = i  i¹⁰ = -1  i¹¹ = -i  i¹² = 1
>> //
>> func ImagPowN(n int) complex128 {
>> if n == 0 {
>> return 1
>> }
>> switch n % 4 {
>> case 1:
>> return 1i
>> case 2:
>> return -1
>> case 3:
>> return -1i
>> }
>> return 1
>> }
>>
>> And this benchmark test:
>> var (
>> imagpownRes complex128
>> )
>>
>> func BenchmarkImagPowN(b *testing.B) {
>> var res complex128
>> for i := 0; i < b.N; i++ {
>> for n := 0; n < 200; n++ {
>> res = ImagPowN(n)
>> }
>> }
>> imagpownRes = res
>> }
>>
>> func BenchmarkImagPowNcmplx(b *testing.B) {
>> var res complex128
>> for i := 0; i < b.N; i++ {
>> for n := 0; n < 200; n++ {
>> res = cmplx.Pow(1i, complex(float64(n), 0))
>> }
>> }
>> imagpownRes = res
>> }
>>
>> We get this output (  go test -run=XXX -bench=.  ):
>> BenchmarkImagPowN-32 300   470 ns/op
>> BenchmarkImagPowNcmplx-32  20 10050 ns/op
>>
>> A 20x speed up...
>>
>> Cheers.
>> Dorival
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to golang-nuts...@googlegroups.com .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>
>
> -- 
> Michael T. Jones
> michae...@gmail.com 
>

-- 
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] Computations with complex numbers may be slow if care is not taken

2017-08-03 Thread Dorival Pedroso
Hi,

This is an interesting benchmark:

Given this function:
// ImagPowN computes iⁿ = (√-1)ⁿ
//
//   i¹ = i  i²  = -1  i³  = -i  i⁴  = 1
//   i⁵ = i  i⁶  = -1  i⁷  = -i  i⁸  = 1
//   i⁹ = i  i¹⁰ = -1  i¹¹ = -i  i¹² = 1
//
func ImagPowN(n int) complex128 {
if n == 0 {
return 1
}
switch n % 4 {
case 1:
return 1i
case 2:
return -1
case 3:
return -1i
}
return 1
}

And this benchmark test:
var (
imagpownRes complex128
)

func BenchmarkImagPowN(b *testing.B) {
var res complex128
for i := 0; i < b.N; i++ {
for n := 0; n < 200; n++ {
res = ImagPowN(n)
}
}
imagpownRes = res
}

func BenchmarkImagPowNcmplx(b *testing.B) {
var res complex128
for i := 0; i < b.N; i++ {
for n := 0; n < 200; n++ {
res = cmplx.Pow(1i, complex(float64(n), 0))
}
}
imagpownRes = res
}

We get this output (  go test -run=XXX -bench=.  ):
BenchmarkImagPowN-32 300   470 ns/op
BenchmarkImagPowNcmplx-32  20 10050 ns/op

A 20x speed up...

Cheers.
Dorival

-- 
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] Minecraft and Go (with project Malmo)

2017-03-30 Thread Dorival Pedroso
Hello, Everybody:

If you like Minecraft and Go, you may like project Malmo 
 and the 
GoWrapper I have been working on (https://github.com/cpmech/malmo forked 
from here ).

For example, a minimal code to command Steve (he will run like a crazy 
person...) is given below (see more examples here 
):

package main

import (
"fmt"
"malmo"
"math/rand"
"os"
"time"
)

func main() {

agent_host := malmo.NewAgentHost()
defer agent_host.Free()

err := agent_host.Parse(os.Args)
if err != nil {
fmt.Println(err)
return
}

my_mission := malmo.NewMissionSpec()
defer my_mission.Free()

my_mission_record := 
malmo.NewMissionRecordSpecTarget("/tmp/saved_data.tgz")
defer my_mission_record.Free()

err = agent_host.StartMissionSimple(my_mission, my_mission_record)
if err != nil {
fmt.Println(err)
return

}

fmt.Println("Waiting for the mission to start")
for {
fmt.Print(".")
time.Sleep(100 * time.Millisecond)
world_state := agent_host.GetWorldState()
if world_state.HasMissionBegun {
break
}
}
fmt.Println()

for {
agent_host.SendCommand("move 1")
agent_host.SendCommand(fmt.Sprintf("turn %d", rand.Int()*2-1))
time.Sleep(500 * time.Millisecond)
world_state := agent_host.GetWorldState()
if !world_state.IsMissionRunning {
break
}
}
fmt.Println("Mission has stopped.")
}


Installation instructions for Ubuntu are here: 
build_ubuntu_minimal_python_and_golang.md 


It should work on Windows and macOS too.

Have (lots of) fun!
Cheers.
Dorival

-- 
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: directory name versus package name

2017-03-29 Thread Dorival Pedroso
I like the idea that the go tool would enforce matching directory and 
package names.

This would help us in case we forget to be consistent...

On Wednesday, March 29, 2017 at 5:18:52 PM UTC+10, Dorival Pedroso wrote:
>
> Hello,
>
> I haven't noticed that the code below (located at *$GOPATH/src/MyWrapper*
> ):
>
> package mylib
>
> import "fmt"
>
> func SayHello() {
> fmt.Println("hello")
> }
>
> is actually being installed (go install) as a *MyWrapper* package, even 
> though the package name was explicitly given as *mylib*.
>
> I couldn't find in the documentation where the handling of this situation 
> is described; i.e. how the final package name is decided (apparently the 
> directory name is chosen).
>
> Anyway, so, why using *package mylib* then?
>
> Cheers.
> Dorival
>
>
>

-- 
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] directory name versus package name

2017-03-29 Thread Dorival Pedroso
Hello,

I haven't noticed that the code below (located at *$GOPATH/src/MyWrapper*):

package mylib

import "fmt"

func SayHello() {
fmt.Println("hello")
}

is actually being installed (go install) as a *MyWrapper* package, even 
though the package name was explicitly given as *mylib*.

I couldn't find in the documentation where the handling of this situation 
is described; i.e. how the final package name is decided (apparently the 
directory name is chosen).

Anyway, so, why using *package mylib* then?

Cheers.
Dorival


-- 
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] Who Loves Go?

2016-08-14 Thread Dorival Pedroso
Hello Everyone,

I'm preparing a list of people / companies that use Go and *really like Go*.

The plan is to present this to a large crowd of undergraduate students (and 
others).

So, suggestions are very welcome!

Many thanks.
Dorival

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [go-nuts] Re: Go 1.6.1 Link problem on Windows:

2016-06-22 Thread Dorival Pedroso
oh, bad news... I was expecting this to be fixed in 1.7...

On Wed, Jun 22, 2016 at 10:33 PM <saurabh.deo...@gmail.com> wrote:

> I am having the same issues with go1.6.2... I also tried go1.7beta2 with
> no luck.
> C:\Go\pkg\tool\windows_amd64\link.exe: running gcc failed: exit status 1
>
> c:/program files/mingw-w64/x86_64-4.8.1-posix-seh-rt_v3-rev2/mingw64/bin
> /../lib/gcc/x86_64-w64-mingw32/4.8.1/../../../../x86_64-w64-mingw32/lib
> /../lib/libntdll.a(dmads01971.o):(.idata$5+0x0): multiple definition of
> `__imp_sqrt'
> c:/program
> files/mingw-w64/x86_64-4.8.1-posix-seh-rt_v3-rev2/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.8.1/../../../../x86_64-w64-mingw32/lib/../lib/libmsvcrt.a(dygcs01179.o):(.idata$5+0x0):
> first defined here
>
>
>
> On Wednesday, April 20, 2016 at 7:06:28 PM UTC-7, Dorival Pedroso wrote:
>>
>> Hi,
>>
>> I'm just wondering what is the cause of the following error (multiple
>> definition of __something)?
>> C:\Go\pkg\tool\windows_amd64\link.exe: running gcc failed: exit status 1
>> C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/lib/../lib/libntdll.a(dyyls01966.o):(.idata$5+0x0):
>> multiple definition of `__imp_pow'
>>
>> This only happens on Windows10 but on Ubuntu/Linux.
>>
>> The Go code makes a call to LAPACK via a C interface as follows:
>> package main
>>
>> /*
>> #cgo CFLAGS: -O3
>> #cgo linux   LDFLAGS: -lm -llapack -lgfortran -lblas
>> #cgo windows LDFLAGS: -lm -llapack -lgfortran -lblas -LC:/GoslDeps/lib
>>
>> #include 
>>
>> void dgesvd_(const char* jobu, const char* jobvt, const int* M, const
>> int* N, double* A, const int* lda, double* S, double* U, const int* ldu,
>> double* VT, const int* ldvt, double* work,const int* lwork, const int*
>> info);
>>
>> int lapack_svd(double *U, double *S, double *Vt, long m_long, double *A) {
>> int m = (int)(m_long);
>> int info  = 0;
>> charjob   = 'A';
>> int lwork = 10*m;
>> double* work  = (double*)malloc(lwork*sizeof(double));
>> dgesvd_(,   // JOBU
>> ,   // JOBVT
>> , // M
>> , // N
>> A,  // A
>> , // LDA
>> S,  // S
>> U,  // U
>> , // LDU
>> Vt, // VT
>> , // LDVT
>> work,   // WORK
>> , // LWORK
>> ); // INFO
>> free(work);
>> return info;
>> }
>> */
>> import "C"
>>
>> import (
>> "fmt"
>> "math"
>> "unsafe"
>> )
>>
>> func main() {
>> A := []float64{1, 2, 3, 2, -4, -9, 3, 6, -3} // col-major format
>> m := int(math.Sqrt(float64(len(A
>> I := func(i, j int) int { return j*m + i }
>> printmat(m, A, "A")
>> U := make([]float64, len(A))
>> S := make([]float64, len(A))
>> Vt := make([]float64, len(A))
>> info := C.lapack_svd(
>> (*C.double)(unsafe.Pointer([0])),
>> (*C.double)(unsafe.Pointer([0])),
>> (*C.double)(unsafe.Pointer([0])),
>> (C.long)(m),
>> (*C.double)(unsafe.Pointer([0])),
>> )
>> fmt.Printf("SVD: info = %d\n", info)
>> USVt := make([]float64, len(A))
>> for i := 0; i < m; i++ {
>> for j := 0; j < m; j++ {
>> for k := 0; k < m; k++ {
>> USVt[I(i, j)] += U[I(i, k)] * S[k] * Vt[I(k, j)]
>> }
>> }
>> }
>> printmat(m, USVt, "U*S*Vt")
>> }
>>
>> func printmat(m int, M []float64, msg string) {
>> fmt.Printf("%s =\n", msg)
>> for i := 0; i < m; i++ {
>> for j := 0; j < m; j++ {
>> fmt.Printf("%13.8f", M[j*m+i])
>> }
>> fmt.Println()
>> }
>> }
>>
>> Any help is much appreciated.
>>
>> Cheers.
>> Dorival
>>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "golang-nuts" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/golang-nuts/fW4KZQ05G_8/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>
-- 

Dorival Pedroso PhD +61 0420411142 www.cpmech.com Brisbane Australia

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