Re: [go-nuts] how to merge different struct to one struct

2019-08-24 Thread jake6502
On Saturday, August 24, 2019 at 3:39:27 AM UTC-4, Lee Rick wrote:
>
> think that there are two struct, they have different fields, hope that 
> there has a function merge(a,b interface{}) interface{}, input param are 
> any two struct, they may have same-type, or have different-type. output 
> param is a struct that composed the two input struct, example type A 
> sturct{Name string}, type B struct{Age int}, a,b :=A{"xxx"},B{10} called 
> c:= merge(a,b), c is interface{}, and 
>
> import "github.com/google/go-querystring/query",
>
> v, _ := query.Values(opt)
> fmt.Print(v.Encode()) // will output: "name=xxx=10"
>
>
>
This still sounds very much like the XY Problem . 
If you goal is really to combine two structs for the purpose of encoding 
them using the net/url Value type, then the using reflection to create a 
new type is probably overly complicated and inefficient. A much simpler, 
and more idiomatic, way to achieve the same result would be to merege the 
url.Value's created from two calls to query.Values(). Something like:
package main

import "fmt"
import "github.com/google/go-querystring/query"

type A struct{ Name string }
type B struct{ Age int }

func main() {
a := A{Name: "foo"}
b := B{Age: 7}

va, _ := query.Values(a)
vb, _ := query.Values(b)

for k, vslice := range vb {
fmt.Println("Key: ", k, "Value: ", vslice)
for _, v := range vslice {
va.Add(k, v)
}
}
fmt.Print(va.Encode())
}
This is just an example, and the combining logic could be pulled out into a 
general function. 

If on the other hand, you have a situation where you are passing an 
interface{} to code *over which you have no control*, then reflection *may *be 
the best way. However, you should probably refernce the specific code (over 
which you have no control) so others could help find a possible solution 
based on you actual problem. 

-- 
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/6d1b0d03-4c20-4fe0-a307-7ce7487d61fc%40googlegroups.com.


[go-nuts] Re: Empty cpu profile file?

2019-08-21 Thread jake6502


On Tuesday, August 20, 2019 at 7:58:29 PM UTC-4, joe mcguckin wrote:
>
> Using Dave Cheney's profile package to figure out the execution path of a 
> library I'm trying to understand.
>
> The application starts, (it's a server), I hit ^c after a couple of 
> minutes, and the console says
>
> Stopping Profiling
> Stopping
>
> Main() catches the console interrupt:
> signal.Notify(c, os.Interrupt)
> log.Info("Stopping")
>
> But the cpu profile file is empty. Is there a way to force is to sync 
> before exiting?
>

Have you looked at this thread? 
https://groups.google.com/d/topic/golang-nuts/YhnyJDI3IG0/discussion 

-- 
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/2aca2638-cc06-4c9a-9eee-88efca612862%40googlegroups.com.


[go-nuts] Re: What did you see at GopherCon 2019 (San Diego)?

2019-08-06 Thread jake6502
On Tuesday, August 6, 2019 at 7:35:08 AM UTC-4, Akram Ahmad wrote:
>
> For me, attending GopherCon 2019 recently in San Diego was tremendous fun 
> (The Gopher community is so amazing!) 
>
> This is what I saw, the following being *the coordinates* to my 
> (incredibly unofficial) writeup: 
>
> *What I Saw at GopherCon 2019* 
> 
>
>
> You'll be able to tell—a whole minute and a half into the writeup 
> above—that I’m taking inspiration from the inimitable Irish playwright and 
> polemicist George Bernard Shaw when he spilled his beans and said that, *My 
> method is to take the utmost trouble to find the right thing to say, and 
> then to say it with the utmost levity* 
>
> Oh, and the following—it happens to be *Section 4*—will probably qualify 
> as the single most serious section in this GopherCon 2019 roundup:
>
> 4. Woohoo, Speaker Highlights [image: ]
>
>
> In full candor, I was oh-so pleased by the high quality of the talks. I 
> sure learned a ton of Go programming tactics, techniques, and strategies to 
> bring back and apply to my own work . For 
> the past one year—and this is to establish some context so we’re on the 
> same page—yours truly, an industry veteran in the area of architecting and 
> implementing distributed computing software systems, and used to 
> extensively wielding tools from the Java 
> 
>  and Scala 
>  
> ecosystems, 
> has been swimming full-time in the ocean that has arisen from the amazing 
> language that is Go.
>
>
> Relax, I’m not about to go meta; to drive the marine metaphors home, 
> though, let’s just say that the beaches of San Diego were an especially 
> appropriate venue for hosting the conference.
>
>
> Back to the GopherCon 2019 talks now. These are the ones that stand out, 
> and here I present merely a snapshot impression each. So in no particular 
> order, other than this being the order in which I recall them, they were by 
> the following speakers:
>
>
>- *Elena Morozova:* I appreciated a lot how Elena’s talk (*How Uber 
>   “Go”es *) was 
>   delightfully replete with helpful, thoughtful, and often times humorous 
>   illustrations which shone a new light on an indispensable subject: How 
> does 
>   one go about maintaining a large codebase for maximum readability and 
>   minimal overhead? In addition to being really well done, the talk was 
>   candid. Elena shared the challenges Uber faced in that 
> process—including 
>   places where they ran into the occasional failure or two—yet emerged 
> with 
>   successful solutions. Referring back to my notes, I remember now that 
> Elena 
>   had also talked about actually introducing a software tool to actually 
>   *enforce* consistent code structure (“Glue” was that project name, 
>   and I’ll definitely be visiting that soon). All in all, excellent talk. 
>   Neat stuff.
>   - *Marwan Sulaiman:* The terrific thing about Marwan’s talk (*Handling 
>   Go Errors *) was 
>   the incredibly deftness with which he walked us through an actual use 
> case 
>   of going about solving a complex problem by *thinking* in the 
>   unique paradigms of Go (Anyone remember the excellent *Thinking in 
>   Java* book from way back when? Hint: I want its counterpart for 
>   Go!) Anyhow, I can attest to the wisdom of resisting the urge to go 
> your 
>   own way; instead, the way to go is to lean on the philosophy with which 
> Go 
>   has been designed to solve programming problems. And hey, even if 
>   error-handling is not your heartthrob topic—I honestly can’t claim it 
> has 
>   ever been mine—the way Marwan brought programmable errors to life (in 
> how 
>   you can design your own architecture in this area, enabling you to get 
> a 
>   solid grip on system failures) was cool. I was wowed. Frankly, an 
>   outstanding talk.
>   - *Mat Ryer:* If I were asked to point to (only) one talk which did 
>   an outstanding job of stripping away all *accidental* complexity, 
>   leading me and others in the audience to keep a laser sharp focus 
> instead 
>   on the *essential* complexity of problem-solving in the domain at 
>   hand—adhering to the elegance of the Go way of doing things—it would be 
>   Mat’s talk (*How I Write HTTP Web Services After Eight Years 
>   *). So I’ve done 
>   this sort of thing at least 17 different ways in the past—using 
> assorted 
>   tools from  libraries that have evolved around more mature languages 
> such 
>   as 

[go-nuts] Re: go 1.13 changes

2019-07-29 Thread jake6502
Also the blog: Next steps toward Go 2 


On Sunday, July 28, 2019 at 1:49:31 PM UTC-4, peterGo wrote:
>
> rob solomon,
>
> Go 1.13 Release Notes: https://tip.golang.org/doc/go1.13
>
> peter
>
>
> On Sunday, July 28, 2019 at 12:02:14 PM UTC-4, rob wrote:
>>
>> I recently saw a description including rationale and historical 
>> references regarding the new features being added to version 1.13. 
>>
>> Now I cannot find that description on the site. 
>>
>> Where is it?  What's the url? 
>>
>> --rob solomon 
>>
>>
>>

-- 
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/7ef2c540-e84c-4f7b-89e7-8cacfc290e38%40googlegroups.com.


[go-nuts] Re: Preparing defaults for multiple-values-returning functions

2019-07-23 Thread jake6502
(Previous post deleted to to premature "Post")

My 2 cents. I'm a seasoned Go programmer with years of professional Go 
experience, and decades of coding work. 

Personally, I would avoid goto if possible. It may "have been a best 
practice for a long time" in C/C++ and other languages. But in Go, I find 
there are usually better ways to write such code. The are situations where 
a goto for exit cleanup is the clearest solution, but I recently worked on 
a 50k line group project where we only did it once. 

Another, a personal preference - I dislike bare returns in *most *situations. 
I know I am not alone in this opinion. Specifying the return values 
explicitly is just clearer, avoids a class of bugs, and can make reading 
the code quicker and easier. 

func ret2(b bool) (int, int) {
 if b {
return 1, 2
}
return 2, 3
}
Or 
func ret2(b bool) (x, y int) {
x = 1
y = 2
if b {
return x, y
}
return 2, 3
}
Of course, the second one only makes sense if there are multiple returns 
that use the "defaults". 

When writing Go code, I think it is always good practice to consider 
readability. Locality is a big part of that. With a bare return there is 
fundamental information "missing" at the point of the return. 


On Monday, July 22, 2019 at 2:51:43 PM UTC-4, Tong Sun wrote:
>
> I want to define a default set of values for the multiple-values-returning 
> function, so when doing error checking along the way, I can return such 
> default set when things go wrong.
>
> How can I do that? 
> Is it possible to make the 17&18 line of the following working?
> https://play.golang.org/p/OX6QwWXc2ch
>
> thx
>
>

-- 
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/167c5b5e-a084-4deb-a299-93e84ca660af%40googlegroups.com.


[go-nuts] Re: Preparing defaults for multiple-values-returning functions

2019-07-23 Thread jake6502
On Monday, July 22, 2019 at 2:51:43 PM UTC-4, Tong Sun wrote:
>
> I want to define a default set of values for the multiple-values-returning 
> function, so when doing error checking along the way, I can return such 
> default set when things go wrong.
>
> How can I do that? 
> Is it possible to make the 17&18 line of the following working?
> https://play.golang.org/p/OX6QwWXc2ch
>
> thx
>
>
My 2 cents. I'm a seasoned Go programmer with years of professional Go 
experience, and decades of coding work. 

Personally, I would avoid goto if possible. It may "have been a best 
practice for a long time" in C/C++ and other languages. But in Go there are 
usually better ways to write code. The are situations where a goto for exit 
cleanup is the clearest solution, but I recently worked on a 50k line 
project where we only did it once. 

Another, a personal preference - I dislike bare returns in most situations. 
I know I am not alone in this opinion. Specifying the return values 
explicitly is just clearer, avoids a class of bugs, and can make reading 
the code quicker and easier. 

func ret2(b bool) (int, int) {
 if b {
return 1, 2
}
return 2, 3
}
Or 
func ret2(b bool) (x, y int) {x=1
y=2
if b {
return 
} else {
x,y = 2, 3
return 





-- 
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/b1b11fcd-5796-49b0-9346-1a222c6a6e32%40googlegroups.com.


Re: [go-nuts] Tools or debug options for debugging 'Error in `bin/main': double free or corruption (fasttop)' in cgo

2019-07-15 Thread jake6502

>
> I am a beginner with GO and cgo, and have never dealt with C corruption 
> issues.
>
> First, I would try really hard to find a pure go solution to your problem, 
or next best, a solution that uses a 3rd party go package that handles the 
cgo for you. I understand that this may not be possible. 

Using cgo is diving right into what is the (arguably) most difficult, 
confusing, error prone, advanced part of the language. Go is a really great 
language, and one of its features is its simplicity. I find that beginners 
in go write better, more reliable, and more readable code with less of a 
learning curve than most languages. However, this does *not* apply to using 
cgo. I'm suspect that some people come to go and get put off because they 
start with cgo, or one of the other "danger areas". 

I always suggest that those new to go focus on writing idiomatic code in 
pure go. Completely avoid cgo, the "unsafe" package, and reflection. 

Which ever way you go, I wish you the best of luck. 
 

-- 
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/084f07f7-6dad-4b1b-bd87-42b9ec45660f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [go-nuts] Avoiding resource leaks with racing channels

2019-07-10 Thread jake6502


On Tuesday, July 9, 2019 at 12:27:32 PM UTC-4, Dan Eloff wrote:
>
> I couldn't use <-channel.Close since in my case the goroutine isn't 
> guaranteed to have something sent, so that would leak goroutines. I added a 
> cleanup goroutine to scan timed-out channels and close them, which solves 
> this problem. But now I can use that close as a signal to the receiver than 
> the a timeout happened, and eliminate the select and the race entirely. The 
> close can in rare cases race with the sender, but that's easily enough 
> fixed:
>
> // TrySend tries to send on a possibly closed channel and handles the 
> panic if necessary.
> // Returns true if conn was successfully sent over the channel.
> func (waiter *Waiter) TrySend(conn Connection) (sent bool) {
> defer func() {
> r := recover()
> sent = r != nil
> }()
> waiter.channel <- conn
> return
> }
>
>
So I guess the best thing to do in these cases is don't combine select with 
> sending unmanaged resources over a channel. It's probably worth warning 
> about this problem in the docs for select? It's not an obvious gotcha.
>

The best thing to do is to not use unmanaged resources. This is obviously 
not always possible, but when you *have* to use unmanaged resources, and 
you care about cleaning them up, you must use a lot of care. This is not a 
problem specific to select. It is possible to correctly use select with 
unmanaged resources. It just takes more thought, and a really solid 
understanding of the language and the principals of concurrency and 
ownership to get it right. 

-- 
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/683f05e8-00d3-4480-90f9-e8c114cb5ca1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: is there a goroutine scope global veriable ?

2019-06-19 Thread jake6502
This has been discussed many times before. Searching "local storage" on 
this group brings up many discussions, including:

https://groups.google.com/d/topic/golang-nuts/Nt0hVV_nqHE/discussion
https://groups.google.com/d/topic/golang-nuts/_Vv7Bzn8yH4/discussion
https://groups.google.com/d/topic/golang-nuts/zuWWBHKn6iw/discussion

My take is that GLS could be genuinely useful in a few cases, but would 
undoubtedly lead to abuse in most cases. In the vast majority of  
situations, what you really want to track, or log, is the specific work 
being done, not actually which goroutine it happens to be running on. For 
example, tracking a specific request, etc. My advice is to pass around a 
context, or some other identifying information about the specific work 
being done. At first this will seem tedious and annoying, but you will 
likely get used to it.


On Tuesday, June 18, 2019 at 10:59:09 PM UTC-4, hui zhang wrote:
>
> is there a goroutine scope global veriable ?
> like  fork a variable from main ?
>

-- 
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/53512dd1-8c24-460d-9bf5-646ea1e95d0f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: Scheduling - find the overlap size of two sequential date ranges and determine the actual dates of included in the intersection

2019-06-17 Thread jake6502
On Sunday, June 16, 2019 at 12:52:54 PM UTC-4, John More wrote:
>
> Updated playground code
> https://play.golang.org/p/qHufIG5ppww
>
> On Sunday, June 16, 2019 at 12:48:25 PM UTC-4, John More wrote:
>>
>> I have created a program to solve this problem (
>> https://play.golang.org/p/BueQBahUUbk) but I am not a pro and do not 
>> know if there is a better way. 
>>
>> Thanks for your time and a huge than You to Yudai the creator of "
>> github.com/yudai/golcs" . I have also attached the code.
>>
>>
>>  
A couple of comments. Without  actually doing the work myself, I would say 
there should be a number of ways to do this using simple date math. This 
should be made easier since you are only concerned with days and not times. 
Creating and walking slices may work, but it seems clumsy and certainly 
inefficient. Also, you code mixes together the code that creates the sample 
data with the actual work all in main().  Refactoring the code to contain a 
function that takes the 4 dates and returns the overlap, and then using 
that function in main, with the sample data, would make it easier to read, 
understand, and refactor. 

-- 
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/cfd6bc73-fb14-4840-9d55-f7293e72bf3b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [go-nuts] Pointer Method Receiver

2019-06-17 Thread jake6502


On Sunday, June 16, 2019 at 5:29:49 PM UTC-4, andrey mirtchovski wrote:
>
> Hi Ali, 
>
> I understand your desire to provide useful information about Go in 
> blog posts. This is commendable. However let's try to keep this list 
> for technical issues and keep empty posts containing just a link to a 
> minimum. More signal, less noise. Is there a particular issue you'd 
> like to raise? Is there a particular item you'd like to address? Let's 
> talk about that. 
>
> There are plenty of aggregators that will cheerfully accept your link: 
> /r/golang, HN, slashdot. There people can vote whether a particular 
> item is of interest. Here, it's just a mailing list. The more noise, 
> the less people are willing to monitor it, and the less real issues 
> get addressed. 
>
> Sincerely, 
>
>
Not looking for a flame war, but I see this kind of post with some 
regularity in this group, usually with no complaints. I see how it could 
get out of hand, but at the current levels, I find these posts helpful, or 
at worst innocuous. So that's another perspective. Thanks Ali for the post. 

-- 
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/c5de9bf2-bbc4-41ad-a4f0-7906fe574b9b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: global var available in different files (same package)

2019-06-07 Thread jake6502


On Friday, June 7, 2019 at 2:12:22 PM UTC-4, Natxo Asenjo wrote:
>
>
>
> On Friday, June 7, 2019 at 6:07:09 PM UTC+2, jake...@gmail.com wrote:
>>
>>
>>
>> It is unclear  what the problem is. Global variables will be accessible 
>> from any file that is part of package "main". As you said, you could 
>> convert the strings in main(), then put them in some global variables, for 
>> use by you other functions. That way you wold not have to be passing them 
>> around. Or am I missing something?
>>
>
> yes, I understand it's unclear, if you do not fully understand something 
> it's difficult to put it into words.
>
> What I mean is that if I convert the var url URL to a string type variable 
> (in this case I need to pass the uri around I get from the cli flag), and 
> this conversion takes places forcefully after parsing the cli args, in func 
> main(), then the new string variable is not passed to the second file. I 
> need to pass it as an argument to the function I want to execute in the 
> second file.
>
> so first file:
>
> func main() 
> {   
> 
> kingpin.MustParse(app.Parse(os.Args[1:]))   
> uri := 
> *url 
> fmt.Println(uri.String(), "from 
> main.go")   
>   
>   
>
> 
> whatever()  
> }
>
> second file:
>
> func whatever() {
>  
> fmt.Println(uri.String(), "from ww.go")
> }
>
> $ go run *.go -u kk 
> # command-line-arguments
> ./ww.go:10:14: undefined: uri
>
> But the url var is available, I just need to unpack it everytime, which is 
> tedious.
>
> I hope I made it clearer now. It's not really an issue but a question to 
> find a better way if possible ;-)
>
> Thanks,
>
> regards,
> Natxo
>

If I understand correctly, you should just be able to convert once, in 
main(), and store it in a global. Something like (code untested):
==kinpingtest.go=
package main

import (
"gopkg.in/alecthomas/kingpin.v2"
"os"
)

var (
app= kingpin.New("shittytest", "shitty kingpin test")
url= app.Flag("url", "url for app").Required().Short('u').URL()
domain = app.Flag("domain", "domain for app").Short('d').Required().
String()
realURL string
)

func main() {
kingpin.MustParse(app.Parse(os.Args[1:]))
realURL = *url.String() 
   
whatever()
}

end kingpintest.go
and second file:

=otherfile.go
package main

import (
"fmt"
)

func whatever() {
fmt.Println(realURL + "/that")
fmt.Println(*domain)
}

===endotherfile.go===

Note that whatever() simply acccesses the global variable realURL that you 
set in main().  I think that does what you want. 
 

-- 
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/d0b4c872-b410-4c62-91ce-db57b127feb9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: global var available in different files (same package)

2019-06-07 Thread jake6502


On Thursday, June 6, 2019 at 3:07:22 PM UTC-4, Natxo Asenjo wrote:
>
> hi,
>
> I'd like to define a couple of global variables in a small cli app. The 
> app has a few files but it's not large.
>
> What I'd like is to use cli flags to define options, and those options 
> should be available for all the functions. I quite like the fact that the 
> content of the variables is checked for correctnes.
>
> Code (using kingpin):
>
> ==kinpingtest.go=
> package main
>
> import (
> "gopkg.in/alecthomas/kingpin.v2"
> "os"
> )
>
> var (
> app= kingpin.New("shittytest", "shitty kingpin test")
> url= app.Flag("url", "url for app").Required().Short('u').URL()
> domain = app.Flag("domain", "domain for 
> app").Short('d').Required().String()
> )
>
> func main() {
> kingpin.MustParse(app.Parse(os.Args[1:]))
> 
> whatever()
> }
>
> end kingpintest.go
> and second file:
>
> =otherfile.go
> package main
>
> import (
> "fmt"
> )
>
> func whatever() {
> u := *url
> fmt.Println(u.String() + "/that")
> fmt.Println(*domain)
> }
>
> ===endotherfile.go===
>
> And quit unsurprisingly, running it:
>
> $ go run *.go --url http://this.com --domain kk.kk
> http://this.com/that
> kk.kk
>
> The 'problem' I have is that I cannot use the variables directly and have 
> to convert them to strings first, and as far as I can see I cannot do that 
> globally because the kingpin arguments get parsed in main(). 
>
> I see one possible solution, and that is to convert the vars to strings in 
> main() and pass those as arguments to funcs called from main().
>
> Are there better options for what I want to achieve (certainly must be, I 
> am just a go newbie)?
>
> Thanks in advance.
>
> Regards,
> Natxo
>

It is unclear  what the problem is. Global variables will be accessible 
from any file that is part of package "main". As you said, you could 
convert the strings in main(), then put them in some global variables, for 
use by you other functions. That way you wold not have to be passing them 
around. Or am I missing something?

Of course, the use of globals raises style issues, but that is a different 
discussion.

-- 
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/2a9c0a4b-5714-4e02-9316-cdc063b9ce3a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: A good indicator of code quality

2019-06-07 Thread jake6502
On Thursday, June 6, 2019 at 3:58:19 PM UTC-4, Carl wrote:
>
> I'd like to know what people are using to measure the quality of their Go 
> code bases and why. Specifically, I'm asking if:
>
>1. There is a way to score a code base on quality that works with 
>idiomatic Go
>2. Use this metric in a CI system and fail the build if the quality 
>falls
>3. Use this metric in a team to detect trends over time and hot spots 
>where technical debt tends to accumulate
>
> It strikes me that Go is quite different to the usual set of popular 
> languages and that even the most basic measures (cyclomatic complexity for 
> example) may not be a good fit. 
>
> For example:
>
>1. Adding proper error handling increases measured complexity, but is 
>actually preferable to not handling errors
>2. A switch case where a case statement contains one or more commas is 
>actually more maintainable, but would probably have the same score as 
>individual case statements on separate lines
>
> There are already a lot of tools that analyse Go code in several different 
> ways - but which ones really work in the long term? 
>
> I'd like to ask the community which ones you've had good experiences with 
> - a test of a good tool could be that a better score results in more 
> idiomatic, maintainable code.
>

I like https://github.com/golangci/golangci-lint for linting, it can give 
you some ideas of stuff to look at. 

I don't know the reasons why you want such metrics, but I would strongly 
caution against equating any automated metric with "code quality". 
Personally, I would never choose to work somewhere where my code was judged 
based on automated metrics. In my opinion, the only way to get good code is 
to hire competent programmers, and require code reviews for all new code. 

Barring code because it fails some heuristic, seems like a recipe for 
coders playing stupid tricks that makes good code bad, but also make it 
pass the test. I have heard such stories in my decades coding. 
 

-- 
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/826b1b63-6d05-4f58-abd8-062de87d8e9b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: pprof - Trouble getting any data from pprof.StartCPUProfile()

2019-05-21 Thread jake6502


On Tuesday, May 21, 2019 at 12:54:32 PM UTC-4, Russtopia wrote:
>
> Hi all, 
>
> I've tried running some of my Go code using CPU Profiling enabled as 
> described at 
>
> https://blog.golang.org/profiling-go-programs 
>
> and 
>
> https://golang.org/pkg/runtime/pprof/#StartCPUProfile 
>
> .. I'm on Funtoo Linux x86_64, and I ensured CONFIG_HIGH_RES_TIMERS=y; 
> however, it seems no matter what I always end up with a profile output 
> file of zero bytes. 
>
> I tried adding the HTTP endpoint for /debug/ to see profiling and 
> heap, allocs, and a few others do yield data.. it's just a few such as 
> pprof are always 0. 
>
> 1. Is there another kernel config I might be missing for supporting this? 
> 2. There's mention elsewhere of the SIGPROF signal, does my program 
> *need* to listen for this signal and receive one or more to actually 
> yield pprof data? 
>
> Thanks, 
> -Russ 
>

I know it is kind of obvious, but are you absolutely sure that 
StopCPUProfile is getting called? 

-- 
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/55c24ac9-79ae-4b44-9471-97a9fa187f85%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: net.InterfaceAddrs() error and returned addr slice

2019-05-16 Thread jake6502


On Wednesday, May 15, 2019 at 5:00:26 PM UTC-4, Vasiliy Tolstov wrote:
>
> Hi! I have error from net.InterfaceAddrs() like route ip+net: no such 
> network interface 
> i think that error happened because i have docker running that 
> creates/deletes interfaces in my system. 
> My question is - does returned slice from InterfaceAddrs filed always, 
> or in case of error in always nil? As i understand go uses netlink to 
> get all interfaces and when tries to get address from interface that 
> already gone, this error happened. 
> In my case this error not fatal, i only need to know all local unicast 
> addresses. So if some interface is gone - this is not fatal, but i 
> need to get all available ip. 
> So if this function not fills the slice , i need to use different 
> method to get all addresses. 
>
> Can you helps me? 
> P.S. Error not easy to reproduce in my case, so i can't easy check 
> does InterfaceAddrs slice filled in case of error. 
>   
>

In Go it is customary that nothing should be assumed about the other return 
values when there is an error. Since the  InterfaceAddrs documentation 
 does not specify what the Addr 
slice contains on error, you should make no assumptions. 

That said, looking at the code, it looks like most or all of the error 
paths will return a nil slice. 

However, the InterfaceAddrs documentation 
 does suggest an alternative. 
It says: "use Interfaces and 
Interface.Addrs  for more 
detail." So you could try using that, and ignore any interfaces that return 
an error. 

-- 
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/c8580226-56ba-4647-b4d2-4948498f9755%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: guarantees on net.Conn and net.UDPConn Read

2019-05-13 Thread jake6502
On Thursday, May 9, 2019 at 2:54:17 AM UTC-4, kortschak wrote:
>
> The Conn and UDPConn Read methods look like io.Reader Read methods, but 
> there is no explicit claim that Conn is an io.Reader. Are the Read 
> methods of these two types identical in behaviour to io.Reader? 
>
 
I can not say definitively, but on unix, UDPConn.Read() is actually 
net.conn.Read() , whch 
calls net.netFD.Read(), which in turn calls poll.FD.Read() 
. You can see there 
in the code:

// Read implements io.Reader.

The windows and plan9 versions also land in Read() functions that have the same 
comment. So it seems to me that UDPConn.Read() is an io.Reader. Of course, that 
only means that it conforms to the requirements of io.Reader 
.

Specifically, are the reads allowed to fill the buffer with arbitrary 
> numbers of bytes in 0 <= len(p) <= n? 
>
 
Yes, according to io.Reader  docs, an 
implementation may do that. Looking at the actual implementations of the 
poll.FD.Read functions, I would say that it seems like they will always 
return the full UDP packts, if it is <= len(p). A full search of the 
relevant platform docs would be required to say definitively. 


> Also, can UPDConn.Read fill the buffer with more than one packet if the 
> buffer would accommodate that? (I am guessing yes, and that if this is 
> important then the ReadFrom method should be used). 
>
>
It looks to me like this will in fact read one packet at a time on amd64 
unix. The function will return after a single successful syscall(SYS_READ) 
which, IIUC will just be one packet for UDP. Since there is no actual 
documentation guaranteeing this, you would have to look at the source code, 
and platform docs, for every platform you care about to be 100% sure. 
However, if it did not work this way, it would make UDP programming very 
hard, or even impossible. So I think it very likely. 
 

> thanks 
> Dan 
>


 

-- 
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/4de7bd5d-5ee5-4ca1-99c9-bba25556134d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [go-nuts] What happens to global vars when main() ends ?

2019-05-04 Thread jake6502
On Friday, May 3, 2019 at 9:44:05 PM UTC-4, lgo...@gmail.com wrote:
>
> I'm currently working on a specialized encryption system where the keys 
> are global...
> More importantly, I've been unable to locate any decent on-line docs 
> describing exactly how Go GC works from a functional programming 
> perspective..I found some docs describing various GC concepts and others 
> that indicate how difficult a problem GC is, but nothing that tells me how 
> Go's GC system works from a programmers perspective i.e. what happens when 
> a function ends ? when main() ends ? 
>  
>
> I recall other discussions in this group about secure memory. At least one 
person suggested https://github.com/awnumar/memguard. Probably worth 
looking at, and doing more searching before reinventing the wheel. 
 

>
> On Friday, May 3, 2019 at 8:50:00 PM UTC-4, Matt Harden wrote:
>>
>> On Fri, May 3, 2019, 17:28  wrote:
>>
>>> Does Go GC  destroy all global vars prior to the end of main() ? 
>>>
>>
>> What do you mean by "destroy"? Go is not an object oriented language and 
>> doesn't have the concept of a destructor. So no, it doesn't, but it also 
>> doesn't need to.
>>
>> May I ask, what led you to ask this question?
>>
>

-- 
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] Is it possible to simplify this snippet?

2019-05-01 Thread jake6502


On Wednesday, May 1, 2019 at 8:41:46 AM UTC-4, Jan Mercl wrote:
>
> On Wed, May 1, 2019 at 2:37 PM гусь > 
> wrote: 
> > 
> > if rl.IsKeyDown(rl.KeyA) { 
> > p.Rect.X -= 1 
> > } 
> > if rl.IsKeyDown(rl.KeyD) { 
> > p.Rect.X += 1 
> > } 
> > if rl.IsKeyDown(rl.KeyW) { 
> > p.Rect.Y -= 1 
> > } 
> > if rl.IsKeyDown(rl.KeyS) { 
> > p.Rect.Y += 1 
> > } 
>
> A switch statement would be perhaps more readable and certainly better 
> performing on average. 
>

To clarify. A switch would not work correctly if it was possible for more 
than one of these to be true. 

I would also point out that go is about creating clear and readable code. 
It is less about writing compact code than many other languages. This takes 
some getting used to. For example, in C this could be done in two lines 
using ternary operators. There is nothing wrong with the code you 
presented. It is clear and readable. If you find that it clutters the 
function too much, then make it into it's only utility function. 

-- 
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: Parsing Raw Syslog messages

2019-04-25 Thread jake6502
This group works on a longer timeframe. It is not uncommon for it to take a 
day or two to get a good response. Bumping your post 8 hours later is 
definitely considered bad etiquette here. 

On Thursday, April 25, 2019 at 4:57:04 AM UTC-4, Nitish Saboo wrote:
>
> Hi,
>
> I want to parse raw syslog messages in GO.Similar to glossy npm, which is 
> a very generic yet powerful library for  parsing raw syslog messages, How 
> can we parse raw syslog message in GO ?
>
> Can I make use of this link '
> https://github.com/nanobox-io/golang-syslogparser/blob/master/rfc3164/rfc3164.go
>  
> '
>  
> for parsing the raw syslog messages ?
>
 
Looks like that is what it is there for.  Give it a try. However, it looks 
to me like you would actually want to use the top level package: 
https://github.com/nanobox-io/golang-syslogparser.

Good Luck

-- 
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: Is there a way to force to pass some function or error check when Debugging?

2019-04-24 Thread jake6502


On Tuesday, April 23, 2019 at 1:43:52 AM UTC-4, hui zhang wrote:
>
> I am debugging a linux server program in local mac machine.
> some code related to environment check , such as check mount point etc.
>
> I want to pass this check ,   how ?
>
>- I try it set return error var to nil.  but it seems not working in 
>devel for now.
>- I imagine to mock function, but not sure how to do it when debugging.
>- I knew the convenient way is to change source code directly .   But 
>there is a lot of code to change .  I don't want to mess it up
>
> any advice?
>
>
Your post is far to vague for me to even begin giving advice. I would 
suggest that you try to give more detail so that we can get a clear picture 
of what you have and what you are trying to accomplish.  

-- 
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: gcwaiting=1 will causes block all the goroutines?

2019-04-11 Thread jake6502
On Wednesday, April 10, 2019 at 10:44:38 PM UTC-4, mount...@gmail.com wrote:
>
> Thank you very much for your meticulous reply. I basically understand the 
> scheduling mechanism, but I still don’t understand the third paragraph.
>
> It is  "It is also important to note that the behavior of runtime.GC() is 
> not the exactly same as the normal backgound GC that gets run by the 
> runtime. In particular runtime.GC() will block until GC is completed, 
> whereas the noral gc does most of its work while allowing the program to 
> continue running. "
>

I apologize if this confused you. It is not directly related to your code, 
which I believe would have the same problem if gc were run automatically by 
the runtime. 

I will try to explain. I have not looked at the runtime code, just the 
documentation and experience, but this is my understanding. Normally 
garbage collection (gc) is run automatically by the go "runtime" code as 
needed. It is also possible to do gc using the function *runtime.GC()*. I 
was pointing out that there are differences between the two. When run 
automatically there are two, *very brief*  "stop the world" periods at the 
beginning and end of gc process. In between those, your code will run. When 
calling *runtime.GC()*, according to the documentation 
, it "blocks the caller until the 
garbage collection is complete. It may also block the entire program." Due 
to this, calling this function is useful if you need to ensure that gc has 
been run. However, it is not useful for simulating the performance or 
behavioral impact of the gc that is run automatically by the go runtime 
code.  

Hope that helps clarify. 



> 在 2019年4月11日星期四 UTC+8上午12:12:01,jake...@gmail.com写道:
>>
>> As Ian said, your question is not completely clear. I think you are 
>> Saying that "I got scheduled!" prints 3 times, then the program appears to 
>> "hangs" on the runtime.GC() call.
>>
>> To start with, it is usually helpful to create a *minimal *program when 
>> dealing with questions like this. Your program can be reduced to 
>> https://play.golang.org/p/-9ekKOxyVoc:
>> package main
>>
>> import (
>> "fmt"
>> "runtime"
>> "time"
>> )
>>
>> func deadloop() {
>> for {
>> //runtime.Gosched()
>> }
>> }
>> func main() {
>>
>> go deadloop()
>>
>> i := 3
>> for {
>> time.Sleep(time.Second * 1)
>> i--
>> fmt.Println("I got scheduled!", i)
>> if i == 0 {
>> runtime.GC() //will set gcwaiting=1, causes other goroutines 
>> not to be scheduled
>> }
>> }
>> }
>> This prints:
>> I got scheduled! 2
>> I got scheduled! 1
>> I got scheduled! 0
>> Then hangs. 
>>
>> I believe that what you are seeing is a result of the GC needing to 
>> briefly pause all goroutines. Go uses something like cooperative 
>> multithreading for goroutines. Your deadloop() function can not be 
>> preempted under the current implentation of the go compiler. So the call to 
>> runtime.GC() hangs waiting to pause all goroutines. If you un comment the 
>> runtime.Gosched() call on line 11, then your program will work as expected. 
>>
>> The details of premtion are implementation dependant, and work is being 
>> done to improve the situation. There is a lot of information available, but 
>> if you have a long running loop that makes no function calls, then it is a 
>> good idea to call runtime.Gosched() every so often.
>>
>> It is also important to note that the behavior of runtime.GC() is not the 
>> exactly same as the normal backgound GC that gets run by the runtime. In 
>> particular runtime.GC() will block until GC is completed, whereas the noral 
>> gc does most of its work while allowing the program to continue running. 
>>
>> Hope that helps.
>>
>>
>> On Wednesday, April 10, 2019 at 7:51:52 AM UTC-4, mount...@gmail.com 
>> wrote:
>>>
>>> Hi,
>>>
>>> My  macos has 4 cores, but i start 3 goroutines, 2 sub goroutines, 1 
>>> main goroutine. 
>>> After main goroutine  exec 3 times  output, triggering gc causes 
>>> gcwaiting=1.
>>> Finally all goroutine blocking
>>>
>>> package main
>>>
>>> import (
>>> "fmt"
>>> "log"
>>> "net/http"
>>> _ "net/http/pprof"
>>> "runtime"
>>>
>>> // "runtime"
>>> "time"
>>> )
>>>
>>> func deadloop() {
>>> for {
>>> }
>>> }
>>> func main() {
>>> go func() {
>>> log.Println(http.ListenAndServe("localhost:6060", nil))
>>> }()
>>>
>>> go deadloop()
>>>
>>> i := 3
>>> for {
>>> time.Sleep(time.Second * 1)
>>> i--
>>> fmt.Println("I got scheduled!")
>>> if i == 0 {
>>> runtime.GC() //will set gcwaiting=1, causes other goroutines not to be 
>>> scheduled
>>> }
>>> }
>>> }
>>>
>>

-- 
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: gcwaiting=1 will causes block all the goroutines?

2019-04-10 Thread jake6502
As Ian said, your question is not completely clear. I think you are Saying 
that "I got scheduled!" prints 3 times, then the program appears to "hangs" 
on the runtime.GC() call.

To start with, it is usually helpful to create a *minimal *program when 
dealing with questions like this. Your program can be reduced to 
https://play.golang.org/p/-9ekKOxyVoc:
package main

import (
"fmt"
"runtime"
"time"
)

func deadloop() {
for {
//runtime.Gosched()
}
}
func main() {

go deadloop()

i := 3
for {
time.Sleep(time.Second * 1)
i--
fmt.Println("I got scheduled!", i)
if i == 0 {
runtime.GC() //will set gcwaiting=1, causes other goroutines 
not to be scheduled
}
}
}
This prints:
I got scheduled! 2
I got scheduled! 1
I got scheduled! 0
Then hangs. 

I believe that what you are seeing is a result of the GC needing to briefly 
pause all goroutines. Go uses something like cooperative multithreading for 
goroutines. Your deadloop() function can not be preempted under the current 
implentation of the go compiler. So the call to runtime.GC() hangs waiting 
to pause all goroutines. If you un comment the runtime.Gosched() call on 
line 11, then your program will work as expected. 

The details of premtion are implementation dependant, and work is being 
done to improve the situation. There is a lot of information available, but 
if you have a long running loop that makes no function calls, then it is a 
good idea to call runtime.Gosched() every so often.

It is also important to note that the behavior of runtime.GC() is not the 
exactly same as the normal backgound GC that gets run by the runtime. In 
particular runtime.GC() will block until GC is completed, whereas the noral 
gc does most of its work while allowing the program to continue running. 

Hope that helps.


On Wednesday, April 10, 2019 at 7:51:52 AM UTC-4, mount...@gmail.com wrote:
>
> Hi,
>
> My  macos has 4 cores, but i start 3 goroutines, 2 sub goroutines, 1 main 
> goroutine. 
> After main goroutine  exec 3 times  output, triggering gc causes 
> gcwaiting=1.
> Finally all goroutine blocking
>
> package main
>
> import (
> "fmt"
> "log"
> "net/http"
> _ "net/http/pprof"
> "runtime"
>
> // "runtime"
> "time"
> )
>
> func deadloop() {
> for {
> }
> }
> func main() {
> go func() {
> log.Println(http.ListenAndServe("localhost:6060", nil))
> }()
>
> go deadloop()
>
> i := 3
> for {
> time.Sleep(time.Second * 1)
> i--
> fmt.Println("I got scheduled!")
> if i == 0 {
> runtime.GC() //will set gcwaiting=1, causes other goroutines not to be 
> scheduled
> }
> }
> }
>

-- 
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: Using Closures to Generate Code On the Fly

2019-04-04 Thread jake6502
Looking at 
https://git.parallelcoin.io/loki/gists/src/commit/d6cabfd0933d0cda731217c371e0295db331ebb1/tailrecursion-generic.md
 
,
 
I am wondering why you put in pseudocode, instead of actual code that can 
be run? Does this require a language change? If so, you might want to make 
that clear. If not, then providing runnable code would be helpful. 

Also, I wonder about statements like:

> If it happens that during compilation the compiler finds that several 
> parts can be merged, the actual execution that results will likely be 
> inlined as well.
>
I think you might be overestimating the go compiler. Have you actually 
tried this to see what inlining and optimizations actually occur?



On Wednesday, April 3, 2019 at 5:45:45 PM UTC-4, Louki Sumirniy wrote:
>
> I have been doing a lot of work involving essentially declarative 
> (nominally) complex data types involving several layers of encapsulation.
>
> I had seen here and there examples of this 'Fluent' method-based pipeline 
> chaining, with methods passing through receivers to invoke multiple 
> distinct functions in the type. Here is a gist about it with an example:
>
>
> https://git.parallelcoin.io/loki/gists/src/commit/d6cabfd0933d0cda731217c371e0295db331ebb1/tailrecursion-generic.md
>
> It occurred to me that if one used this to construct complex graphs of 
> processing, that the CPU's branch predictor would probably be on fire for 
> that time, since even though these binary blobs are being possibly 
> arbitrarily constructed based on random inputs, they will have a 
> substantial amount off scope in common, so...
>
> It might then be possible to further amplify this effect by allowing the 
> runtime to lay the code ahead of the execution a bit like Magneto pulling 
> those metal blocks up as he walks forwards.
>
> I don't know how verbose it is, just at first blush, I am generally not 
> fond of closure syntax in Go, but it seems to me like this dynamic 
> construction pattern would be very good for speeding up complex processing 
> with significant variance in sequence.
>
> For example, playing back a journal into a database - a scouting thread 
> could pre-process some of the key but simple and salient data about the 
> segments of the journal, and construct ahead of time cache locality 
> optimised code and data segmentation that will run with 100% confidence 
> based on the structure and composition of the data.
>
> At the moment I am just using it to chain validators together, but, for 
> example, generating a graph from a blockchain ledger, in order to perform 
> validation, can have a front-running pass that first generates the 
> join/split paths of tokens intersecting with accounts. This graph forms the 
> map of how to process the data, and for parallelisation, such a graph would 
> allow the replay processing to be split automatically to make optimal use 
> of cores, caches and memory bus. It could even farm the work out acrosss 
> the network and all of the cluster nodes process their mostly isolated 
> segment, then share their database tables directly and voila.
>
> Such processing is naturally easier to construct using recursion, and with 
> composition of closures in this way, it should also be quite efficient. 
> Although at with current go 1.10+ syntax it is a little clumsy, each part 
> is small and this helps a lot.
>
> When I am making big changes to code, I have this sensation like I am 
> walking on unstable ground, because sometimes I can get a way into 
> something and discover I passed the correct route some way back and I 
> didn't commit before it and now I have to start all over again.
>
> Small pieces less than a screenful at a time are very manageable. Just 
> gotta get a handle on that vertigo :)
>

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


[go-nuts] Re: Confusing Behavior When Compiling an Assignment Using a Map

2019-03-29 Thread jake6502
Yes, that is expected. The right hand side of the assignment is 
`b[1].code`. That is a single value. The "magic" that allows a two value 
return from a map lookup does not carry through to more complex expressions 
that use the value from that lookup. It would get confusing really fast if 
it did. 

On Friday, March 29, 2019 at 11:16:03 AM UTC-4, jlfo...@berkeley.edu wrote:
>
>
> go version go1.12 linux/amd64
>
> When compiling the example program below (
> https://play.golang.org/p/koHORLMMuhK)
> I get the error
>
> assignment mismatch: 2 variable but 1 values
>
> for the assignment statement in Part 2 but the assignment statement in 
> Part 1 compiles.
> Both assignment statements have the same number of values, but it appears 
> that
> referencing an integer in a structure field in the 2nd assignment 
> statement, rather than a simple
> integer, confuses the compiler.
>
> I know I can work around this problem by breaking Part 2 into 2 assignment
> statements, the first assigning a structure, and the second assigning the 
> structure field, but
> I wonder if what I'm seeing is expected.
>
> Cordially,
> Jon Forrest
>
> ---
>
> package main
>
> import "fmt"
>
> var a = map[int]int{
> 1: 2,
> }
>
> var b = map[int]Word{
> 1: {2, 3},
> }
>
> type Word struct {
> codeint
> scratch int
> }
>
> func main() {
> var num int
>
> // Part 1
> num, ok := a[1]
> if ok {
> fmt.Println(num)
> }
>
> // Part 2
> num, ok = b[1].code   // assignment mismatch: 2 variable but 1 
> values
> if ok {
> fmt.Println(num)
> }
> }
>
>
>

-- 
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: [ANN] another attempt at desktop ui

2019-03-29 Thread jake6502
No mention of what platforms it supports. You may want to add that to the 
docs also. 

On Friday, March 29, 2019 at 5:46:29 AM UTC-4, Johann Freymuth wrote:
>
> Over the last few months I've tried to write a desktop GUI library that 
> takes a slightly different approach to traditional GUI libraries. It uses 
> ideas from immediate mode UI in order to be very lightweight and hopefully 
> somewhat idiomatic.
>
> https://github.com/jfreymuth/ui
>
> The API is now stable enough that I would like people to look at it and 
> provide feedback about the design and usability.
> I'm looking forward to hearing your opinions.
>
>

-- 
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: rand.Rand.Seed() vs rand.NewSource()

2019-03-27 Thread jake6502
Following up on Ian's post. It is generally a good idea to go to the 
playground  and make a minimal working "program" 
to demonstrate your question before posting. In doing so you would have 
discovered that the zero value of a rand.Rand can not be used, and will 
panic. 

Also, a tip. You can go to the docs for NewSource at 
https://golang.org/pkg/math/rand/#NewSource, then click on the "NewSource"  
link, and get to the source code at 
https://golang.org/src/math/rand/rand.go?s=1614:1647#L34, which may be 
informative. 



On Tuesday, March 26, 2019 at 2:48:27 PM UTC-4, Liam wrote:
>
> Could anyone clarify the difference between these two?
>
> r := rand.New(rand.NewSource(...))
>
> var r rand.Rand; r.Seed(...)
>
>

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


[go-nuts] Re: Need Help- Suddenly my unit test stop working

2019-03-25 Thread jake6502
First off, there is something really wrong with your post. Colors make it 
almost unreadable. Please stick to non-colored (black) text, and for output 
text please paste text directly, or use the code block feature provided by 
the google groups website. 

Have you looked at the file "C:\Users\Gini Joseph\GoWorkspace\pkg\mod\
github.com\stretchr\testify@v1.3.0\mock\mock_test.go" and verified that it 
matches https://github.com/stretchr/testify/blob/v1.3.0/mock/mock_test.go ? 
Is it possible that the file was corrupted of modified? Maybe try deleting 
the package and re-downloading?

Also, it might be a good idea to list your go version and platform.


On Monday, March 25, 2019 at 11:42:19 AM UTC-4, Merry wrote:
>
> In go if i am running the unit test test the follwing error appears
>
> # github.com/emisgroup/auth/lambda/user_service/add_role
> package github.com/emisgroup/auth/lambda/user_service/add_role (test)
> imports github.com/emisgroup/auth/library/datastore/datastoremocks
> imports github.com/stretchr/testify/mock: 
> \GoWorkspace\pkg\mod\github.com\stretchr\testify@v1.3.0\mock\mock_test.go:1:1:
>  
> expected 'package', found 'EOF'
> FAILgithub.com/emisgroup/auth/lambda/user_service/add_role [setup 
> failed]
> Error: Tests failed.
>

-- 
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: Launching a windows app from command line with paths in arguments problem

2019-03-21 Thread jake6502
It is likely that the spaces before the command line arguments is confusing 
the Chrome parser. Try removing them for every item in Args, and it may 
work. 

On a style note, I would use:

AppCommand:=
`C:\Users\User\AppData\Local\Google\Chrome\Application\chrome.exe`

 instead of:

AppCommand:=
"C:\\Users\\User\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"





On Thursday, March 21, 2019 at 12:13:52 PM UTC-4, XXX ZZZ wrote:
>
> Hello,
>
> I'm trying to launch Chrome from Go under windows, some of the arguments 
> I'm passing have custom paths in it and it seems that go is sanitizing 
> these arguments and not recognizing the paths. Basically it seems to be 
> appending the application path into the arguments with a path.
>
> Code is as follows:
>
> package main
>
> import(
> "os/exec"
> "fmt"
> )
>
> func main(){
> fmt.Printf("Trying to start Chrome\n")
>
> 
> AppCommand:="C:\\Users\\User\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"
> Args:=[]string{" --user-data-dir=\"C:\\ProfileTest 1\"",
> " --load-extension=\"C:\\test\"",
> " --disk-cache-dir=\"C:\\profileCache\"",
> " --disable-preconnect",
> " --dns-prefetch-disable",
> " --start-maximized",
> " --allow-insecure-localhost",
> " --ignore-certificate-errors",
> " --ignore-certificate-errors-spki-list",
> " --no-default-browser-check",
> " --disable-infobars"}
>
> cmd := exec.Command(AppCommand,  Args...)
> //stdout, err := cmd.Output()
> if err := cmd.Start(); err != nil {
> fmt.Printf("Start Chrome error %+v\n", err)
> continue
> }
> }
>
> At chrome, we noticed that the load-extension path is being appended with: 
> "C:\\Users\\User\\AppData\\Local\\Google\\Chrome\\Application\\" so it ends 
> up with: 
> "C:\\Users\\User\\AppData\\Local\\Google\\Chrome\\Application\\""C:\\test", 
> same goes for the other arguments with a path.
>
> Is there any way to tell go to avoid doing this? Maybe just executing a 
> command straight from a command line?
>
> 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.


Re: [go-nuts] Re: Deferring a close that can fail

2019-03-21 Thread jake6502
Two things to note about this. 

First, if the "everything else" deferred to might include a return 
statement, then this could result in the same "silent failure" behavior.

Secondly - use this pattern with great caution. It is critical to confirm 
that a double close on ifDB is explicitly allowed. For example, if you have 
an io.Closer , then, according to the 
documentation, the behavior of a double close is not specified. IMHO, if 
the package documentation does not explicitly allow double close, I would  
consider doing so to to be a bug.


Only do this if you can confirm that a double close on  ifDB

On Thursday, March 21, 2019 at 6:11:04 AM UTC-4, rog wrote:
>
> This issue is why I like having idempotent close. Do:
>
>defer ifDB.Close()
>
> but also, after everything else is complete, do:
>
> if err := ifDB.Close(); err != nil {
> handle error case
> }
>
> That way if you return early on error your connection is still closed, but 
> you can still write the obvious code for checking the close error when 
> everything else has succeeded.
>
>
> On Thu, 21 Mar 2019 at 09:41, Amnon Baron Cohen  > wrote:
>
>> The idiomatic Go way is to write
>>
>>defer  ifDB.Close()
>>
>> Simple is better than clever.
>>
>> + Readability does matter.
>>
>>
>> And in situations where you really need to check that the connection was 
>> successfully closed, and
>> you have a workable scheme for recovering from this situation, then write 
>> a named helper function
>> which encompasses this logic, rather than writing a convoluted anonymous 
>> function.
>>
>> And make sure that all the execution paths in this function have unit 
>> tests.
>>
>>
>>
>> On Tuesday, 19 March 2019 23:57:51 UTC, David Collier-Brown wrote:
>>>
>>> It's a known bad thing to defer a close for anything buffered, as 
>>> discussed at https://www.joeshaw.org/dont-defer-close-on-writable-files/
>>> but some constructs lack a Sync() call.
>>>
>>> For example, I have code like
>>> ifDB, message, err := OpenInflux(server, debug)
>>> if err != nil {
>>> // If this fails, fail fast so we notice
>>> panic(fmt.Errorf("failed to open and ping influxDB, %s 
>>> %v",
>>> message, err))
>>> }
>>> defer func() {
>>> err = ifDB.Close()
>>> if err != nil {
>>> // This may be a harmless, very bad thing
>>> panic(fmt.Errorf("failure closing connection to 
>>> influxDB, %v", err))
>>> }
>>> }()
>>>
>>>
>>> which closes an influxDB database, but will panic if the close fails.
>>>
>>> Separate logic makes sure I have passed the point at which the data is 
>>> committed before I commit my reading of input, so eventually the data will 
>>> be reread and rewritten. Nevertheless, this is exceedingly complex, and the 
>>> comment sums it up: "a harmless, very bad thing".
>>>
>>> Is there an idiomatic way to address this? I ended up reading influxDB 
>>> code and doing all sorts of deranged safety-critical-system DFAs to 
>>> reassure myself this will actually work, but every time I do that, my brain 
>>> hurts!
>>>
>>> --dave
>>>
>>>
>>> -- 
>> 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: panic at fmt.Printlb

2019-03-18 Thread jake6502
Can't say for sure without seeing additional code. But it looks like you 
have a race condition. 

It appears that the fmt.Println() is trying to print the map at the same 
time that you are modifying it. Your locks may prevent ForEachRemov() and  
FindAndRemove() from accessing the map at the same time, but the 
fmt.Println() is done without any protection. So it could be reading the 
map (for printing) while either ForEachRemov() or FindAndRemove() are 
modifying (writing to) the map. 


On Sunday, March 17, 2019 at 7:28:10 PM UTC-4, liaoy...@gmail.com wrote:
>
> Hi,
> I got a panic when i run my test code
> my go version is 'go version go1.12 linux/amd64'
>
> panic: reflect: call of reflect.Value.Type on zero Value
>
> goroutine 6 [running]:
> reflect.Value.Type(0x0, 0x0, 0x0, 0x4db0c0, 0xc183d0)
> /usr/local/go/src/reflect/value.go:1813 +0x169
> internal/fmtsort.compare(0x0, 0x0, 0x0, 0x4e34c0, 0xcb8110, 0xb4, 0x1)
> /usr/local/go/src/internal/fmtsort/sort.go:76 +0x5a
> internal/fmtsort.(*SortedMap).Less(0xcc2000, 0x9, 0x8, 0x100cb8100)
> /usr/local/go/src/internal/fmtsort/sort.go:27 +0x87
> sort.insertionSort(0x525540, 0xcc2000, 0x0, 0xa)
> /usr/local/go/src/sort/sort.go:27 +0xab
> sort.stable(0x525540, 0xcc2000, 0xa)
> /usr/local/go/src/sort/sort.go:368 +0x86
> sort.Stable(0x525540, 0xcc2000)
> /usr/local/go/src/sort/sort.go:357 +0x53
> internal/fmtsort.Sort(0x4e3a00, 0xc12678, 0x1b5, 0x20)
> /usr/local/go/src/internal/fmtsort/sort.go:67 +0x2e3
> fmt.(*pp).printValue(0xcb2000, 0x4e3a00, 0xc12678, 0x1b5, 0x76, 
> 0x2)
> /usr/local/go/src/fmt/print.go:759 +0xd1d
> fmt.(*pp).printValue(0xcb2000, 0x4eb220, 0xc12670, 0x199, 
> 0xc00076, 0x1)
> /usr/local/go/src/fmt/print.go:796 +0x1b52
> fmt.(*pp).printValue(0xcb2000, 0x4f89e0, 0xc12670, 0x16, 0x76, 0x0)
> /usr/local/go/src/fmt/print.go:866 +0x199f
> fmt.(*pp).printArg(0xcb2000, 0x4f89e0, 0xc12670, 0x76)
> /usr/local/go/src/fmt/print.go:702 +0x2ba
> fmt.(*pp).doPrintln(0xcb2000, 0xca9fa0, 0x2, 0x2)
> /usr/local/go/src/fmt/print.go:1159 +0xb2
> fmt.Fprintln(0x524b60, 0xc10018, 0xc387a0, 0x2, 0x2, 0x0, 0x0, 0x0)
> /usr/local/go/src/fmt/print.go:265 +0x58
> fmt.Println(...)
> /usr/local/go/src/fmt/print.go:275
> main.testMapLock.func1(0xc12670, 0xc18350)
> /home/lbs/go/src/demo/test/testmap/testmap.go:78 +0x95
> created by main.testMapLock
> /home/lbs/go/src/demo/test/testmap/testmap.go:77 +0xfa
>
>
> Piece of my code:
> //ForEach range all the node in map and call the handler and then delete 
> the node if the handler return true
> func (em *EMSmap) ForEachRemove ( h DoEachNode ,userData interface{}){
> em.m.Lock()
> defer em.m.Unlock()
> for key,value := range em.emap{
> userData := userData
> if b := h(key, value, userData);b{
> delete(em.emap, key)
> }
> }
> }
>
> //FindAndRemove store the node in a temporary var and then delete it from 
> the map and return the node which stored in the temporary var
> func (em *EMSmap) FindAndRemove (key interface{}) interface{}{
> em.m.Lock()
> defer em.m.Unlock()
> if _,ok := em.emap[key]; !ok{
> return nil
> }
> value := em.emap[key]
> delete(em.emap, key)
> return value
> }
>
>
> func testMapLock(){
> var callMap *emsutil.EMSmap = context.CallMap
> var wgt sync.WaitGroup
> for i := 0; i < 10; i++{
> callMap.Put(i, i)
> }
> wgt.Add(2)
> go func(){
> fmt.Println("ForEachRemove",callMap)
> time.Sleep(time.Duration(10)*time.Millisecond)
> callMap.ForEachRemove(func (key interface{}, value interface{}, userData 
> interface{})bool{
> fmt.Println("delete by ForEachRemove",key,value)
> time.Sleep(time.Duration(2)*time.Millisecond)
> return true}, nil)
> wgt.Done()
> }()
> go func(){
> fmt.Println("FindAndRemove",callMap)
> for i := 0; i < 10; i++{
> val := callMap.FindAndRemove(i)
> fmt.Println("delete by for FindAndRemove",val)
> time.Sleep(time.Duration(2)*time.Millisecond)
> }
> wgt.Done()
> }()
> wgt.Wait()
> wg.Done()
> }
>

-- 
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: gdb go optimized out

2019-03-15 Thread jake6502
First off, we are always happy to have new users in the group. But one more 
bit of etiquette - Please don't post screenshots of text. Instead copy 
paste the text into the message. I like to use fixed width font, or put it 
in a code block. See the recent discussion at 
https://groups.google.com/d/topic/golang-nuts/KR_JXhBWCk8/discussion for 
the many reasons why.

Looking at the screenshot, I see that you are trying to debug into a 
runtime library  function. That is why it is optimized. IIRC, the way you 
have built will only build main.go without optimization, but it will not 
effect the standard libraries. I think you want something like  *go build 
-o main -gcflags "all=-N -l" main.go *. The "all=" is the key here.

Good luck

On Friday, March 15, 2019 at 3:26:28 AM UTC-4, mount...@gmail.com wrote:
>
>
>
> 在 2019年3月15日星期五 UTC+8上午12:49:51,Jake Montgomery写道:
>>
>> First off. Please don't use a giant font in this group. It adds no 
>> valuable information, and makes it seem like you are yelling at the reader.
>>
>> I use delve  not gdb, so I can not 
>> speak directly to that. I use -gcflags="-N -l", and so far it has always 
>> produced a reasonably debuggable (with delve 
>>  at least) executable.
>>
>> Your question is probably too vague to answer though. What, specifically, 
>> are you experiencing as being "optimized out"? If you provided code for a 
>> small sample program, and told us what you actually see, and what you 
>> expect to see, you would have a better chance of a useful response. 
>>
>>
>> On Thursday, March 14, 2019 at 12:03:50 AM UTC-4, mount...@gmail.com 
>> wrote:
>>>
>>>
>>> Very strange, when I compile with go build -o main -gcflags "-N -l" 
>>> main.go, it appears optimized out when debugging with gdb.
>>>
>>> Who knows why?
>>>
>>>

-- 
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: gdb go optimized out

2019-03-14 Thread jake6502
First off. Please don't use a giant font in this group. It adds no valuable 
information, and makes it seem like you are yelling at the reader.

I use delve  not gdb, so I can not speak 
directly to that. I use -gcflags="-N -l", and so far it has always produced 
a reasonably debuggable (with delve  at 
least) executable.

Your question is probably too vague to answer though. What, specifically, 
are you experiencing as being "optimized out"? If you provided code for a 
small sample program, and told us what you actually see, and what you 
expect to see, you would have a better chance of a useful response. 


On Thursday, March 14, 2019 at 12:03:50 AM UTC-4, mount...@gmail.com wrote:
>
>
> Very strange, when I compile with go build -o main -gcflags "-N -l" 
> main.go, it appears optimized out when debugging with gdb.
>
> Who knows why?
>
>

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


[go-nuts] Re: How to retain environment in SSH

2019-03-11 Thread jake6502
Perhaps someone will magically understand your problem. But in general I 
would say that you should post more information if you want a good chance 
of a useful reply. Some tips:

Please never post screenshots unless there is an overwhelming reason to do 
so. This is not one of those cases. Instead copy the *text* and add it in a 
fixed width font or in a code block. 

Post your code, in this case probably ssh-example.go,  so we can know what 
you are doing. If the relevant code is small you can put it directly into 
the post as code block, or put it in https://play.golang.org and use the 
"share" button to get a permalink to your code. This is acceptable even if 
your code will not run in the playground. 

Be as specific as possible. For example, you do not mention what OS you are 
sshing from or to. For SSH, the OS can matter. Also, things like "the proxy 
environment variables" is very vague. More info will give the helpful folks 
of this group more to work with. 

Good Luck


On Monday, March 11, 2019 at 3:00:23 AM UTC-4, Subramanian Sridharan wrote:

> Hi guys!
>
> I would like to know how to keep the environment variables over SSH using 
> Go.
>
> I find that several environment variables are missing when I SSH using Go. 
>
> For instance, the proxy environment variables are not present when I SSH 
> using Go, but they're present when I SSH using an actual terminal.
>
> [image: Screenshot from 2019-03-11 12-28-22.png]
>
> Thanks in advance!
>

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


[go-nuts] Re: Go playground to support none-standard modules

2019-03-10 Thread jake6502
You can setup and run your own playground with 
https://github.com/golang/playground. I have not done it myself, but you 
could probably use that to do what you propose. 



On Saturday, March 9, 2019 at 9:50:15 PM UTC-5, Tong Sun wrote:
>
> I know Go playground does not support none-standard modules. 
> Is there any online site that does support none-standard modules?
>
> For online code-running sites for any other languages, they all 
> support none-standard modules. 
> Go is the only one that I know which doesn't, while godoc is already 
> supporting every possible Go package on earth. 
>
> Hope it'll be changed someday. 
>
> 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: why slice[len:len] okay, but slice[len] fail?

2019-03-08 Thread jake6502
The other answers to your original question are reasonable, and probably 
helpful. But I would also like to point out the definitive, though maybe 
less helpful answer to both your original question, and this new one.  You 
see that behavior because the language specification says you should. Read 
https://golang.org/ref/spec#Slice_expressions, particualrly the "Simple 
slice expressions" section. 

On Thursday, March 7, 2019 at 9:12:28 PM UTC-5, Halbert.Collier Liu wrote:
>
> Yes, i see, 
> thank you so much!
>
> Could you please explain, why primes[6:6] okay, but primes[7:7] not?   
> *:-)*
>
>
> 在 2019年3月7日星期四 UTC+8下午11:55:40,Robert Johnstone写道:
>>
>> Hello,
>>
>> When you use the colon, you taking a subset of the data.  Further, the 
>> notation is a closed/open.  So a slice primes[6:6] is all of the element in 
>> the array with index >= 6 and index < 6, which is an empty set.  Note that 
>> the type of the expression primes[6:6] is []int.
>>
>> When you don't use the colon, you are access a specific element.  Since 
>> the count is zero based, the valid indices are 0 through 5 inclusive.  Note 
>> that the type of the expression primes[6] is simply int.
>>
>> Good luck.
>>
>>
>> On Thursday, 7 March 2019 10:32:04 UTC-5, Halbert.Collier Liu wrote:
>>>
>>> Hi.
>>>
>>> The code like below:
>>>
>>> package main
>>>
>>> import "fmt"
>>>
>>> func main() {
>>> primes := [6]int{2, 3, 5, 7, 11, 13}
>>> fmt.Println(primes[6:6]) .  // *OK*. return:   []
>>> //fmt.Println(primes[6]) .   // fail. out of bounds...
>>> }
>>>
>>> Why? 
>>>
>>> Is the golang grammatical feature? or anything else..
>>>
>>> Any help, please!
>>>
>>

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


[go-nuts] Re: Go 1.12 installer on Windows 7 (x64) problem

2019-03-04 Thread jake6502
I have seen posts, unrelated to Go, about installers not recognizing 
Windows 7 SP1 as being installed. You did a screenshot of the update 
history, but you should also check that it is listed under 
Computer->Properties->Windows edition. See here 
.
 


While it is possible that this is a problem specific to the Go installer, 
most likely it is not. So I suggest googling for other people with similar 
issues installing other software.

Good Luck.

On Monday, March 4, 2019 at 11:06:51 AM UTC-5, Tad Vizbaras wrote:
>
>
> Go 1.12 installer on Windows 7 (x64) problem.
>
> Requires: Windows 7 with Service Pack 1. 
> But Service Pack is installed and restart done twice (just to make sure).
>
> Screenshot attached.
>
> How can I get around installer? Can I force it skip the check?
>
>
>

-- 
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] finding a way to convert "map[string]map[string]Somthing" into "map[string]interface{}"

2019-03-02 Thread jake6502
There have been multiple long discussions about converting []foo to 
[]interface{} in this group. It is not possible. Most of the discussions 
apply just as well to your case. 

If you really need a "generic" function that does this, and can't convert 
as suggested by Louki, then you could use reflection. The function would be 
"func sortedKeys(theMap interface{})", then it would have to dig down 
manually. This would be difficult to write if you are reflection novice. It 
would also be much, much less efficient than the other options.  

On Saturday, March 2, 2019 at 8:10:06 AM UTC-5, 김용빈 wrote:
>
> yes I can do this in a for loop. but that is not I want.
>
> what I really want to do is "create a function that returns sorted 
> []string keys from any map[string]... in type safe way".
>
> when I said 'there is no easy way...' , I mean I cannot create that 
> function easily.
>
> I did not very clarify. sorry for the confusion. 
>
> 2019년 3월 2일 토요일 오후 8시 46분 50초 UTC+9, Louki Sumirniy 님의 말:
>>
>> Only an assigment to a pre-declared map[string]interface{} in a loop 
>> walking the first layer of that complex map type is required to put the 
>> values into that type, it's not complicated and doesn't have to touch the 
>> template. Something like this:
>>
>> var MapStringInterface map[string]interface{}
>> for i,x := range MapStringMapStringThing {
>> MapStringInterface[i]=x
>> }
>>
>> On Saturday, 2 March 2019 11:01:10 UTC+1, 김용빈 wrote:
>>>
>>> Thank you, Mercl.
>>>
>>> So there isn't an easy way, you mean, right?
>>>
>>> 2019년 3월 2일 토요일 오후 6시 45분 8초 UTC+9, Jan Mercl 님의 말:

 On Sat, Mar 2, 2019 at 10:32 AM 김용빈  wrote:

 > but it seems the argument is not automatically converted.

 Things are automatically converted to a different type in Go only when 
 they are assigned to, or passed as arguments of, interface types.

 > manual type cast `map[string]interface{}(myMap)` also not working.
 > is there a way of doing this? 

 Go does not have casts. Conversion rules[0] do not allow a conversion 
 of different map types because the memory layouts are not compatible.

   [0]: https://golang.org/ref/spec#Conversions

 -- 

 -j

>>>

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


[go-nuts] Re: Resolving methods on pointer types

2019-02-24 Thread jake6502
Maybe I'm misunderstanding, but the important thing is that foo never be 
copied. In your example, it is, in fact, *not *copied. See 
https://play.golang.org/p/U5EsDZSO3ce. Note that Foo is copied, but both f2 
and f3 contain the same foo pointer, so the foo was never copied or moved. 
When embedding a *foo, there is no real reason to use a *Foo, and the 
example could be - https://play.golang.org/p/RapUv6AvPK-,

On Sunday, February 24, 2019 at 5:34:27 PM UTC-5, Deomid Ryabkov wrote:
>
> thanks for the suggestion Burak and Jake, however embedding won't do for 
> the same reason as aliasing - it allows copying by value, which i want to 
> prevent (in my real use case foo.bar is a C pointer).
>
> https://play.golang.org/p/4BcOQTGkPiy works, and it should not (f3 := *f2 
> is a no as it makes copy of f2.bar)
>
> On Sunday, February 24, 2019 at 10:07:05 PM UTC, Jake Montgomery wrote:
>>
>> On Sunday, February 24, 2019 at 4:31:10 PM UTC-5, Deomid Ryabkov wrote:
>>>
>>> Why can't Go resolve methods declared on the pointer receiver of the 
>>> destination type?
>>>
>>  
>> Because that  is not how the language was designed. (I'm too busy to look 
>> up the spec here, but it is in there.)
>>
>>>
>>> consider:
>>>
>>> [SNIP]
>>>
>>> (playground link: https://play.golang.org/p/v0f9pYaTJAa )
>>>
>>> it fails to compile with "prog.go:25:23: f2.GetBar undefined (type Foo 
>>> has no field or method GetBar)" but it's not clear to me, why Foo doesn't 
>>> get pointer methods from *foo.
>>>
>>>  
>> You could try using an embedded type to have Foo "inherit" methods from 
>> *foo, like this - https://play.golang.org/p/WvNj5GUjsxe. 
>>
>> Good Luck
>>
>

-- 
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: Resolving methods on pointer types

2019-02-24 Thread jake6502
On Sunday, February 24, 2019 at 4:31:10 PM UTC-5, Deomid Ryabkov wrote:
>
> Why can't Go resolve methods declared on the pointer receiver of the 
> destination type?
>
 
Because that  is not how the language was designed. (I'm too busy to look 
up the spec here, but it is in there.)

>
> consider:
>
> [SNIP]
>
> (playground link: https://play.golang.org/p/v0f9pYaTJAa )
>
> it fails to compile with "prog.go:25:23: f2.GetBar undefined (type Foo has 
> no field or method GetBar)" but it's not clear to me, why Foo doesn't get 
> pointer methods from *foo.
>
>  
You could try using an embedded type to have Foo "inherit" methods from 
*foo, like this - https://play.golang.org/p/WvNj5GUjsxe. 

Good Luck

-- 
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: url.parse issue if the first character of a url is a number

2019-02-12 Thread jake6502
I can not speak directly to Go's version, but according to the IETF 
standards, a domain name can not start with a digit. So they are in fact 
malformed. 

On Sunday, February 10, 2019 at 9:23:54 PM UTC-5, Nathan Xu wrote:
>
> What I said is the url content without http/https . 
>
> On Sunday, February 3, 2019 at 4:09:05 PM UTC+8, Tamás Gulácsi wrote:
>>
>> An url must start with a scheme (i.e. http://).
>
>

-- 
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] lock for assigning to different elements of an array

2019-02-02 Thread jake6502
Always a good read on why that is still a problem:
Benign Data Races: What Could Possibly Go Wrong? 

It is not specific to go, but mostly applies to any language, and is stuff 
all developers should know. 

On Friday, February 1, 2019 at 4:58:11 PM UTC-5, Michael Ellis wrote:
>
>
>
> On Friday, February 1, 2019 at 11:11:24 AM UTC-5, robert engels wrote:
>>
>>
>> for {
>>if A.a > 100 {
>>   break
>> }
>>
>>
>> Go routine #2 may never see the value of A.a change and so never exit the 
>> loop.
>>
>
> I'm confused. I can see how that would fail if the test were A.a == 100 
> since Go routine #1 might increment past 100 before #2 ,  but as written it 
> seems wrong only if the application logic depends on Go routine #2 exiting 
> the loop as soon as A.a reaches 100 (as opposed to any time afterward.) 
>
> What am I missing?
>
>
>>

-- 
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: [ANN] goey - Declarative, cross-platform GUIs

2019-01-29 Thread jake6502
This looks quite interesting for the types of simple apps I'm building 
right now. However, I have discovered a couple of bugs. I don't see any way 
to report them on bitbucket. 

Are you taking bug reports, and if so, what is the best way to communicate 
them?
Are you taking outside pull requests for bug fixes?

Thanks for the great work,


On Thursday, September 6, 2018 at 12:07:41 AM UTC-4, Robert Johnstone wrote:
>
> This is an initial announcement of goey, a package for declarative, 
> cross-platform GUIs.  The range of controls, their supported properties and 
> events, should roughly match what is available in HTML.  However, 
> properties and events may be limited to support portability.  Additionally, 
> styling of the controls will be limited, with the look of controls matching 
> the native platform.
>
> A minimal example of a complete application can be found at 
> https://godoc.org/bitbucket.org/rj/goey/example/onebutton.
>
> * README:  https://bitbucket.org/rj/goey/src/default/README.md
> * godoc: https://godoc.org/bitbucket.org/rj/goey
>
> Feedback welcome.
>
>

-- 
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: What exactly is a method set?

2019-01-20 Thread jake6502
On Sunday, January 20, 2019 at 7:56:39 AM UTC-5, 伊藤和也 wrote:
>
> Yes I did. Can I say a method set is the one which associates an interface 
> with methods?
>
 
Almost. The method set *of an interface* is the set of methods in the 
interface. But other types, aside from interfaces, also have method sets. 
The method set of a type is the set of functions which can be called with 
an object of that type as a receiver. The last line of the spec, connects 
the two. It essentially says that if the method set of an object contains 
all the methods in an interface, then that object implements the interface. 
The object's method set may contain additional methods, but it must 
minimally contain all those in the interface if you want it to implement 
that interface.  Perhaps an example: 

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

type A int

func (a A) foo() {
fmt.Println("A.foo")
}

func (a A) bar() {
fmt.Println("A.bar")
}

func (a A) apple() {
fmt.Println("A.baz")
}

type B int

func (b B) foo() {
fmt.Println("B.foo")
}

func (b *B) bar() {
fmt.Println("B.bar")
}

func (b B) banana() {
fmt.Println("B.baz")
}

type Thinger interface {
foo()
bar()
}


Following the spec at 
https://golang.org/ref/spec#Method_sets which says:
 

> The method set of an interface type 
>  is its interface.
>
 
So the method set of  Thinger is foo() and bar().

The method set of any other type T consists of all methods 
>  declared with receiver 
> type T.
>

So the method set of type A is foo(), bar() and apple(), since they all 
take an A as the receiver. The method set of B is foo() and banana(), since 
they all take a B as the receiver.

The method set of the corresponding pointer type 
>  *T is the set of all methods 
> declared with receiver *T or T (that is, it also contains the method set 
> of T).
>

So the method set of *B (a pointer to B) is foo(), bar() and banana(), 
since they all take a B or a *B as the receiver.

The method set of a type determines the interfaces that the type implements 
>  and the methods that can be 
> called  using a receiver of that type. 
>

So an object of type A implements the Thinger interface.  An object of type 
B does *not *implement the Thinger interface, since it is missing bar(). 
But an object of type *B does implement the Thinger interface. See the 
playground 
version  for examples. 

This may not be 100% correct spec speak, hopefully will give you some sense 
of method sets is in Go. 

Hope this helps a little. 
 

>
> 2019年1月20日日曜日 21時37分23秒 UTC+9 伊藤和也:
>>
>> What exactly is a method set?
>>
>

-- 
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 make the first character in a string lowercase?

2019-01-07 Thread jake6502
I believe he is demostrating an optimization for strings that are already 
in the correct form.

On Monday, January 7, 2019 at 1:45:50 PM UTC-5, robert engels wrote:
>
> Huh? Isn’t your code calling the exact same method ?
>
> On Jan 7, 2019, at 12:22 PM, peterGo > 
> wrote:
>
> Nikolai,
>
> "What is the easiest way to make a string "LikeThis" --> "likeThis"?"
>
> Te easiest is not always the best.
>
> The code should be correct and reasonably efficient. For example,
>
> func firstToLower(s string) string {
> if len(s) > 0 {
> r, size := utf8.DecodeRuneInString(s)
> if r != utf8.RuneError || size > 1 {
> lo := unicode.ToLower(r)
> if lo != r {
> s = string(lo) + s[size:]
> }
> }
> }
> return s
> }
>
> $ go test tolow_test.go -bench=.
> BenchmarkToLow-4300041.3 ns/op 8 B/op1 allocs/op
> BenchmarkLow-4 2 6.96 ns/op0 B/op0 allocs/op
> $
>
> Playground: https://play.golang.org/p/z6CLIS7LaHo
>
> Peter
>
> On Saturday, November 24, 2012 at 5:51:23 AM UTC-5, Nikolai wrote:
>>
>> Hi!
>>
>> What is the easiest way to make a string "LikeThis" --> "likeThis"?
>>
>
> -- 
> 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: C++ 11 to Golang convertor

2019-01-04 Thread jake6502
On Thursday, January 3, 2019 at 5:46:39 PM UTC-5, Eric Raymond wrote:
>
> On Thursday, January 3, 2019 at 12:11:06 PM UTC-5, Jake Montgomery wrote:
>>
>> I would note that any tool that ports from C++, or even C, to Go is going 
>> to produce ugly, unmaintainable, and non-idiomatic code, at best.
>>
>
> These are two different cases.  I agree that graceful C++ to Go 
> transpilation is effectively impossible.
>
> On the other hand, I believe graceful, comment-preserving C to 
> idiomatic-Go transpilation is almost possible.  
>

I might believe that it could be comment-preserving and possible graceful, 
and pretty much human readable. But I seriously doubt that it could ever 
produce anything I would call idiomatic-Go. Perhaps we have different 
definitions of that term. Aside from the line by line form, I also mean 
"something that an experienced go programmer might write." Idomatic-Go by 
my definition, would include the use of things like interfaces and methods. 
It uses goroutines and channels where appropriate. That is what you want if 
you want "real" go code that is usable and maintainable. 

"Transpilation" is really just the first step. It can get you to a working 
code base, but turning it into truly idiomatic Go, that people want to deal 
with, is work that needs to be done by humans. IIUC, that's what the go 
team did with the compiler. Getting a Go version that was 100% 
functionality-faithful to the original C was crucial. But it was only the 
first step. 

-- 
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: C++ 11 to Golang convertor

2019-01-03 Thread jake6502
There are so, so many ways to go about porting functionality from one 
language to another. I hope you have seriously considered why you want to 
make such a port. The answer to that will likely, in part, drive your 
strategy. In addition the nature and size of the code base, and your 
timeline, will effect the strategy used. 

I would note that any tool that ports from C++, or even C, to Go is going 
to produce ugly, unmaintainable, and non-idiomatic code, at best. Turning 
that into real Go code would still be a major project. There is a great 
video about the process that the go team used to convert the compiler from 
C to Go, but I can not find it now. 

Have you considered rewriting from scratch? That can often be less painful 
that one might think, if you already have a really good suite of 
"functional level" tests that you can use to ensure functional continuity. 

Another strategy that comes to mind is to use cgo to do the rewrite one 
component of library at a time. This could be done one of two ways. Either 
keep the program (or library, or whatever it is,) as a C++ app, and call 
into your converted go code. Or, conversely, write a go program that calls 
into C++ for unconverted functionally. 

Of course, with no real information about what you have, or what you are 
trying to achieve, you can only get general advice. 

Good Luck. 


On Wednesday, January 2, 2019 at 10:37:17 PM UTC-5, aureal...@gmail.com 
wrote:
>
> Hello All
>
> I have C++ 11 source files which I need to convert to Go language code
> Is there any converter  tool for this.
> I google quite a few tools, none seems powerful and complete enough to do 
> the job.for me.
> Please help
>
> Thanks
> Abhishek
>

-- 
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: What are the reasonable reasons to use pointers?

2019-01-01 Thread jake6502
What Cris said is one reason. That is, if you need the function being 
called to be able to change the value, then use a pointer. If you pass a 
value instead of a pointer, then changes made by the function being called 
are not visible to the caller. (The situation is more complicated, but that 
is the gist.)

If you do not need the function to be able to change the value, then 
default to using pass by value. In general, pass by value should be your 
default mode. If a pointer is used, there should always be a clear reason. 
Sometimes pointers are used to pass a very large structure, to avoid 
copying. But I would only do that if the copying was demonstrated to be a 
performance issue.  

There is another reason to use pointers. Some objects must never be 
"copied". Passing a struct by value causes it to be copied, and the copy 
sent to the function being called. One example is sync.Mutex 
. The documentation for that states 
that "a Mutex must not be copied after first use." So a sync.Mutex 
 must always be passed by pointer. And 
any struct that contains a non-pointer sync.Mutex would also need to be 
passed by pointer. 

Good Luck.

On Tuesday, January 1, 2019 at 6:34:34 AM UTC-5, 伊藤和也 wrote:
>
> What are the reasonable reasons to use pointers? Are pointers neseccary?
>

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


[go-nuts] Re: Why can't I see the whole stack trace of goroutine

2018-11-08 Thread jake6502
I would point out that this *is *the whole stack trace *of the goroutine*. 
In fact, the actual stack trace is just the first line, since the goroutine 
in question is only one function deep. If you are breaking into your 
program after the leaking has started, then the function that created the 
goroutine has long since exited, and its stack no longer exists. 

What you really want is the stack trace for the goroutine that created the 
leaking goroutine, at the time that the leak was created. I suggest you put 
a break point on (*Transport).dialConn, or 
/usr/local/go/src/net/http/transport.go:1117 and run your program to see 
where these are being created. You might also be able to figure it out by 
looking at the go library source code and tracing back from 
(*Transport).dialConn. In any case, that should give you a place to start.

Good Luck. 

On Tuesday, November 6, 2018 at 10:55:24 PM UTC-5, rickyu...@gmail.com 
wrote:
>
> I have a lot of leaking goroutines in my code over a span of time. I am 
> trying to debug it but I can't seem to figure out from where these are 
> occuring from.
> Any help in finding the source is helpful.
>
>
> goroutine 2329 [select, 1281 minutes]:
> net/http.(*persistConn).readLoop(0xc420a80120)
>   /usr/local/go/src/net/http/transport.go:1599 +0x9ec
> created by net/http.(*Transport).dialConn
>   /usr/local/go/src/net/http/transport.go:1117 +0xa35
>
>
> 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.


Re: [go-nuts] Correct way to solve slice of interface type problem

2018-10-31 Thread jake6502
It is highly likely that when go2 comes out, with generics, it will be 
trivial to write a ToInterfaceSlice() function that takes a slice of any 
type T and returns a []interface{}. 

On Tuesday, October 30, 2018 at 8:35:39 PM UTC-4, Justin Israel wrote:
>
>
>
> On Wed, Oct 31, 2018 at 1:32 PM robert engels  > wrote:
>
>> I have argued for a runtime/built-in to do this - it is so common…. (if 
>> doing “kind of OO” in Go)
>>
>
> I would love to have the ability to do it with built-in support, but I 
> feel like it would go against the goals of not wanting to hide complexity. 
> It wouldn't be "free" to do it (as far as I know) and I doubt the Go 
> maintainers want it to hide the copy into the new slice. My 2 cents.
>  
>
>>
>>
>> On Oct 30, 2018, at 7:30 PM, Justin Israel > > wrote:
>>
>>
>>
>> On Wed, Oct 31, 2018 at 11:21 AM > 
>> wrote:
>>
>>> Hello, everyone.
>>> Consider following code:
>>>
>>> package main
>>> import "fmt"
>>>
>>> type implementation struct {
>>> d []int}
>>>
>>> func (impl *implementation) getData() interface{} {
>>> return impl.d}
>>>
>>> type phase struct{}
>>>
>>> type data interface {
>>> getData() interface{}}
>>>
>>> func MakeIntDataPhase() *phase {
>>> return {}}
>>>
>>> func (p *phase) run(population []data) []data {
>>> return nil}
>>>
>>> func main() {
>>> var population []implementation
>>> MyPhase := MakeIntDataPhase()
>>> fmt.Println(MyPhase.run(population))
>>> }
>>>
>>>
>>> When running following code in playground I got following error: 
>>> prog.go:30:25: cannot use population (type []implementation) as type []data 
>>> in argument to MyPhase.run
>>>
>>> If I understand correctly it is because slice of interface type cannot be 
>>> converted by the compiler to concrete type.
>>>
>>>
>>> What is correct way in golang to implement functionality that is presented 
>>> in the example?
>>>
>>> When method argument defined using a slice of some interface, how I can 
>>> pass it a slice of a concrete type that implements the interface?
>>>
>>>
>> You would end up needing to just do   
>>
>> func (p *phase) run(population {}interface) []data
>>
>> and then type assert the {}interface into []implementation
>> There isn't a way to directly pass a slice of concrete type to a function 
>> that accepts a slice of interface, unless you first do this:
>>
>> iface := make([]data, len(population))
>> for i, p := range population {
>> iface[i] = p
>> }
>> MyPhase.run(iface)
>>
>> Justin
>>
>>>
>>> -- 
>>> You received this message because you are subscribed to the Google 
>>> Groups "golang-nuts" group.
>>> To unsubscribe from this group and stop receiving emails from it, send 
>>> an email to golang-nuts...@googlegroups.com .
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to golang-nuts...@googlegroups.com .
>> For more options, visit https://groups.google.com/d/optout.
>>
>>
>>

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


Re: [go-nuts] interface array and ... operator

2018-10-25 Thread jake6502
In my defense, neither A() nor B() complies in the actual example given. If 
you comment out A() you will see that B() then fails to compile. 

If B() is fixed by replacing "i = append(i, s)" with "i = append(i, sa)", 
then it succeeds. I believe that is due to the clause I referenced in my 
mistaken post.That is 
https://golang.org/ref/spec#Passing_arguments_to_..._parameters which says:

"Otherwise, the value passed is a new slice of type []T with a new 
underlying array whose successive elements are the actual arguments, which 
all must be assignable  to T."

This refers to the case when individual arguments are given. In this case a 
string is assignable to an interface{}. 

IIUC A() fails because later in that section it says:

"If the final argument is assignable to a slice type []T, it may be passed 
unchanged as the value for a ...T parameter if the argument is followed by 
 In this case no new slice is created."

And as we know []string is not assignable to []interface{}.

Hope that makes more sense than my original post.



On Thursday, October 25, 2018 at 12:01:21 PM UTC-4, Robert Engels wrote:
>
> No need. I was just getting very confused trying to follow. 
>
> On Oct 25, 2018, at 10:59 AM, jake...@gmail.com  wrote:
>
> Yes. I was completely mistaken in my post. Apologies. 
>
> On Wednesday, October 24, 2018 at 12:14:36 PM UTC-4, robert engels wrote:
>>
>> I quote
>>
>> So in the OP's example https://play.golang.org/p/59bpr8TCIge, the 
>> function A() is assigning a []string to the variadic ...[]interface{}. 
>> Since string is assignable to interface{}. this is fine. The function B() 
>> is assigning a []interface{} to the variadic of ...[]string. Since 
>> interface{} is *not *assignable to string, this is not allowed. 
>>
>>
>> On Oct 24, 2018, at 11:08 AM, Jan Mercl <0xj...@gmail.com> wrote:
>>
>> Nobody said that.
>>
>> On Wed, Oct 24, 2018, 18:04 robert engels  wrote:
>>
>>> I’m confused… it is A that doesn’t work, and B works… everyone keeps 
>>> stating that B doesn’t work and A works….
>>>
>>> On Oct 24, 2018, at 10:55 AM, jake...@gmail.com wrote:
>>>
>>>
>>> That is correct. The relevant part of 
>>> https://golang.org/ref/spec#Passing_arguments_to_..._parameters is 
>>> where it says: " respective parameter passing rules 
>>> apply". 
>>> This links to 
>>> https://golang.org/ref/spec#Passing_arguments_to_..._parameters which 
>>> says:
>>>
>>> "Otherwise, the value passed is a new slice of type []T with a new 
>>> underlying array whose successive elements are the actual arguments, which 
>>> all must be assignable  to T
>>> ."
>>>
>>> So in the OP's example https://play.golang.org/p/59bpr8TCIge, the 
>>> function A() is assigning a []string to the variadic ...[]interface{}. 
>>> Since string is assignable to interface{}. this is fine. The function B() 
>>> is assigning a []interface{} to the variadic of ...[]string. Since 
>>> interface{} is *not *assignable to string, this is not allowed. 
>>>
>>> Hope that clarifies. 
>>>
>>>
>>> On Wednesday, October 24, 2018 at 9:11:50 AM UTC-4, Robert Engels wrote:

 But it is the varadic one that works according to OP. 

 On Oct 24, 2018, at 4:19 AM, Jan Mercl <0xj...@gmail.com> wrote:

 On Wed, Oct 24, 2018 at 7:34 AM Mayank Jha  
 wrote:

 > why does A() not work while B works here, 
 https://play.golang.org/p/59bpr8TCIge 

 Type mismatch. The compiler is clear about it:

 prog.go:8:12: cannot use s (type []string) as type []interface 
 {} in append

 From https://golang.org/ref/spec#Appending_and_copying_slices

 
 The variadic function append appends zero or more values x to s of type 
 S, which must be a slice type, 
 and returns the resulting slice, also of type S. The values x are 
 passed to a parameter of type ...T
 where T is the element typeof S and the respective parameter passing 
 rules apply. As a special case,
 append also accepts a first argument assignable to type []byte with a 
 second argument of string type
 followed by  This form appends the bytes of the string.
 ---

 In the OP code, type T is `interface{}`, but the appended elements have 
 type `string`. That violates the above quoted specs.


 -- 

 -j

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


>>> -- 
>>> You received this message because you are subscribed to the Google 
>>> Groups "golang-nuts" group.
>>> To unsubscribe from this group and stop receiving emails from it, send 

Re: [go-nuts] interface array and ... operator

2018-10-25 Thread jake6502
Oops. Please ignore my entire post. Misunderstood completely. 

On Wednesday, October 24, 2018 at 11:55:18 AM UTC-4, Jake Montgomery wrote:
>
> That is correct. The relevant part of 
> https://golang.org/ref/spec#Passing_arguments_to_..._parameters is where 
> it says: " respective parameter passing rules 
>  apply". 
> This links to 
> https://golang.org/ref/spec#Passing_arguments_to_..._parameters which 
> says:
>
> "Otherwise, the value passed is a new slice of type []T with a new 
> underlying array whose successive elements are the actual arguments, which 
> all must be assignable  to T."
>
> So in the OP's example https://play.golang.org/p/59bpr8TCIge, the 
> function A() is assigning a []string to the variadic ...[]interface{}. 
> Since string is assignable to interface{}. this is fine. The function B() 
> is assigning a []interface{} to the variadic of ...[]string. Since 
> interface{} is *not *assignable to string, this is not allowed. 
>
> Hope that clarifies. 
>
>
> On Wednesday, October 24, 2018 at 9:11:50 AM UTC-4, Robert Engels wrote:
>>
>> But it is the varadic one that works according to OP. 
>>
>> On Oct 24, 2018, at 4:19 AM, Jan Mercl <0xj...@gmail.com> wrote:
>>
>> On Wed, Oct 24, 2018 at 7:34 AM Mayank Jha  wrote:
>>
>> > why does A() not work while B works here, 
>> https://play.golang.org/p/59bpr8TCIge 
>>
>> Type mismatch. The compiler is clear about it:
>>
>> prog.go:8:12: cannot use s (type []string) as type []interface {} 
>> in append
>>
>> From https://golang.org/ref/spec#Appending_and_copying_slices
>>
>> 
>> The variadic function append appends zero or more values x to s of type 
>> S, which must be a slice type, 
>> and returns the resulting slice, also of type S. The values x are passed 
>> to a parameter of type ...T
>> where T is the element typeof S and the respective parameter passing 
>> rules apply. As a special case,
>> append also accepts a first argument assignable to type []byte with a 
>> second argument of string type
>> followed by  This form appends the bytes of the string.
>> ---
>>
>> In the OP code, type T is `interface{}`, but the appended elements have 
>> type `string`. That violates the above quoted specs.
>>
>>
>> -- 
>>
>> -j
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to golang-nuts...@googlegroups.com.
>> For more options, visit https://groups.google.com/d/optout.
>>
>>

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


Re: [go-nuts] interface array and ... operator

2018-10-25 Thread jake6502
Yes. I was completely mistaken in my post. Apologies. 

On Wednesday, October 24, 2018 at 12:14:36 PM UTC-4, robert engels wrote:
>
> I quote
>
> So in the OP's example https://play.golang.org/p/59bpr8TCIge, the 
> function A() is assigning a []string to the variadic ...[]interface{}. 
> Since string is assignable to interface{}. this is fine. The function B() 
> is assigning a []interface{} to the variadic of ...[]string. Since 
> interface{} is *not *assignable to string, this is not allowed. 
>
>
> On Oct 24, 2018, at 11:08 AM, Jan Mercl <0xj...@gmail.com > 
> wrote:
>
> Nobody said that.
>
> On Wed, Oct 24, 2018, 18:04 robert engels  > wrote:
>
>> I’m confused… it is A that doesn’t work, and B works… everyone keeps 
>> stating that B doesn’t work and A works….
>>
>> On Oct 24, 2018, at 10:55 AM, jake...@gmail.com  wrote:
>>
>>
>> That is correct. The relevant part of 
>> https://golang.org/ref/spec#Passing_arguments_to_..._parameters is where 
>> it says: " respective parameter passing rules 
>> apply". 
>> This links to 
>> https://golang.org/ref/spec#Passing_arguments_to_..._parameters which 
>> says:
>>
>> "Otherwise, the value passed is a new slice of type []T with a new 
>> underlying array whose successive elements are the actual arguments, which 
>> all must be assignable  to T."
>>
>> So in the OP's example https://play.golang.org/p/59bpr8TCIge, the 
>> function A() is assigning a []string to the variadic ...[]interface{}. 
>> Since string is assignable to interface{}. this is fine. The function B() 
>> is assigning a []interface{} to the variadic of ...[]string. Since 
>> interface{} is *not *assignable to string, this is not allowed. 
>>
>> Hope that clarifies. 
>>
>>
>> On Wednesday, October 24, 2018 at 9:11:50 AM UTC-4, Robert Engels wrote:
>>>
>>> But it is the varadic one that works according to OP. 
>>>
>>> On Oct 24, 2018, at 4:19 AM, Jan Mercl <0xj...@gmail.com> wrote:
>>>
>>> On Wed, Oct 24, 2018 at 7:34 AM Mayank Jha  wrote:
>>>
>>> > why does A() not work while B works here, 
>>> https://play.golang.org/p/59bpr8TCIge 
>>>
>>> Type mismatch. The compiler is clear about it:
>>>
>>> prog.go:8:12: cannot use s (type []string) as type []interface 
>>> {} in append
>>>
>>> From https://golang.org/ref/spec#Appending_and_copying_slices
>>>
>>> 
>>> The variadic function append appends zero or more values x to s of type 
>>> S, which must be a slice type, 
>>> and returns the resulting slice, also of type S. The values x are passed 
>>> to a parameter of type ...T
>>> where T is the element typeof S and the respective parameter passing 
>>> rules apply. As a special case,
>>> append also accepts a first argument assignable to type []byte with a 
>>> second argument of string type
>>> followed by  This form appends the bytes of the string.
>>> ---
>>>
>>> In the OP code, type T is `interface{}`, but the appended elements have 
>>> type `string`. That violates the above quoted specs.
>>>
>>>
>>> -- 
>>>
>>> -j
>>>
>>> -- 
>>> You received this message because you are subscribed to the Google 
>>> Groups "golang-nuts" group.
>>> To unsubscribe from this group and stop receiving emails from it, send 
>>> an email to golang-nuts...@googlegroups.com.
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to golang-nuts...@googlegroups.com .
>> For more options, visit https://groups.google.com/d/optout.
>>
>>
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to golang-nuts...@googlegroups.com .
>> For more options, visit https://groups.google.com/d/optout.
>>
> -- 
>
> -j
>
>
>

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


Re: [go-nuts] interface array and ... operator

2018-10-24 Thread jake6502
That is correct. The relevant part of 
https://golang.org/ref/spec#Passing_arguments_to_..._parameters is where it 
says: " respective parameter passing rules 
 apply". 
This links to 
https://golang.org/ref/spec#Passing_arguments_to_..._parameters which says:

"Otherwise, the value passed is a new slice of type []T with a new 
underlying array whose successive elements are the actual arguments, which 
all must be assignable  to T."

So in the OP's example https://play.golang.org/p/59bpr8TCIge, the function 
A() is assigning a []string to the variadic ...[]interface{}. Since string 
is assignable to interface{}. this is fine. The function B() is assigning a 
[]interface{} to the variadic of ...[]string. Since interface{} is *not 
*assignable 
to string, this is not allowed. 

Hope that clarifies. 


On Wednesday, October 24, 2018 at 9:11:50 AM UTC-4, Robert Engels wrote:
>
> But it is the varadic one that works according to OP. 
>
> On Oct 24, 2018, at 4:19 AM, Jan Mercl <0xj...@gmail.com > 
> wrote:
>
> On Wed, Oct 24, 2018 at 7:34 AM Mayank Jha  > wrote:
>
> > why does A() not work while B works here, 
> https://play.golang.org/p/59bpr8TCIge 
>
> Type mismatch. The compiler is clear about it:
>
> prog.go:8:12: cannot use s (type []string) as type []interface {} 
> in append
>
> From https://golang.org/ref/spec#Appending_and_copying_slices
>
> 
> The variadic function append appends zero or more values x to s of type S, 
> which must be a slice type, 
> and returns the resulting slice, also of type S. The values x are passed 
> to a parameter of type ...T
> where T is the element typeof S and the respective parameter passing rules 
> apply. As a special case,
> append also accepts a first argument assignable to type []byte with a 
> second argument of string type
> followed by  This form appends the bytes of the string.
> ---
>
> In the OP code, type T is `interface{}`, but the appended elements have 
> type `string`. That violates the above quoted specs.
>
>
> -- 
>
> -j
>
> -- 
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts...@googlegroups.com .
> For more options, visit https://groups.google.com/d/optout.
>
>

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


[go-nuts] Re: array indexed by derived type?

2018-10-07 Thread jake6502
I'm gonna say no.

On Saturday, October 6, 2018 at 5:07:33 PM UTC-4, Steve Roth wrote:
>
> Is there a way to declare an array (or slice) that is indexed by a type 
> derived from int, rather than indexed by int?  My intent is to have the 
> compiler complain if I index the array/slice with a generic int rather than 
> the specific int-derived type I'm supposed to use.  This will help verify 
> correct usage of the array.  I didn't see any way to do this in the 
> language spec, but hopefully I just missed it?
>
> Thanks,
> Steve
>
>

-- 
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: What can i transport in a channel?

2018-10-02 Thread jake6502
To expand on what Tamás said ... There is really nothing that is not safe 
to transport in a channel. But there are some considerations. 

For example if you transport an *http.**Response* then you will be making a 
copy on the way in and out of the channel. So that *may *not be safe, but 
it has nothing to do with channels, just that some objects are not safe to 
copy. If your value is not safe to copy, then use pointers in your 
channel.  

Another thing to consider is concurrent access. If you send a pointer to an 
object over a channel, but then continue to access is from the sending 
goroutine, you may be creating a race. Even if you pass an object by value, 
so it gets copied, you still need to make sure it does not *contain *any 
pointers, maps, slices, ect, before accessing the original and the copy 
concurrently, since go copy is shallow. 

Hope this helps.

On Tuesday, October 2, 2018 at 1:49:58 AM UTC-4, Patrik Iselind wrote:
>
> Hi,
>
> I came up with a question i cannot answer. Hopefully you guys can clarify 
> things for me.
>
> If i've made a HTTP request and i get the response. I don't touch the body 
> or anything at this point. Would that response be safe to transport in a 
> channel? Having the other end process the response.
>
> A bit more general question; what's not safe to transport in a channel?
>
> Regards,
> Patrik
>

-- 
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: Generics - Why contracts?

2018-09-12 Thread jake6502
Some of the reasons for contracts have been covered by others in this 
thread already. But somehow one of the biggest has not. Contracts make it 
possible to change the implementation of a generic function in a published 
package. Without a contract it would be super easy for a seemingly simple 
change to a published generic function to break clients of that function. 
While not foolproof, the presence of a contract means that, if the contract 
does not change, then changes to the generic code should, minimally, not 
cause compilation errors in client code. And, if intelligently created, 
should offer a degree of confidence that such changes won't functionally 
break client code either. 

Personally, I don't expect they will be hard to write. After decades of 
experience with many languages, my gut tells me that the vast majority of 
contracts written by the vast majority of "general" programmers will be 
trivial. Easily written and read. More advanced contracts would be less 
common, but I suspect that common idioms will quickly emerge for the more 
advanced constraints.

I do have some concerns about reading more complicated contracts. However, 
that can be alleviated by reasonable line commenting of complicated 
contracts. Additionally, if the error messages for violating a constraint 
when calling generic function  are well crafted, that should make it even 
easier. But I would rather have to do some extra thinking on rare occasion, 
than have to learn some whole new language for contracts. 

As for:

It runs parallel to my concerns about language compactness, too.
>
 
Again, I predict  that most contracts will be a few lines long. Secondly, 
golang is not a language of compactness. Many of the design decisions make 
that clear. And idiomatic go favors clarity over brevity. It can be hard to 
adjust to, but overall it's a win. Finally, if you are writing so much 
generic code that the contracts are any appreciable percentage of your code 
base, then you are probably way off the rails anyway. 

My 2¢


On Tuesday, September 11, 2018 at 10:57:30 AM UTC-4, Jeff wrote:

> I am a semi-advanced hobbyist. I have a BSCEE degree, but no professional 
> programming experience.  I have been programming for > 30 years and have 
> written small programs in easily 20+ different languages during that time. 
>  So, while not a professional programmer, I am not exactly a novice.
>
> I've been following some of the contracts proposal discussions and frankly 
> I have been a bit lost.  I think I have a good handle on interfaces, but 
> this contracts stuff confuses me.  One of Go's strengths is that the 
> language is relatively easy to grasp.  The code is generally relatively 
> straightforward.  People seem to draft code that leans more toward 
> readability instead of toward "clever" but less easily understood.  I have 
> looked at the source code of many packages.  It is rare that I cannot 
> follow the code.  I cannot say this about many other languages.  My fear is 
> this contracts proposal will kill my ability to read and understood code of 
> others.
>
> I recall using generics many years ago in Ada and did not recall them 
> being so confusing.  So, I went back and looked at the Ada implementation. 
>  See, e.g., https://en.wikibooks.org/wiki/Ada_Programming/Generics 
> .
>  
>  Honestly, I find this general approach to be easier to follow than 
> contracts.  Based on the link, it has some similarities with C++ templates. 
>  I have some basic experience with C++, but I have no experience with C++ 
> templates.
>
> TLDR; So why contracts and not templates or something else?  Is there a 
> benefit to contracts that I don't appreciate (very likely, cause I don't 
> understand them)?  Are there issues with a template approach?  If this has 
> been addressed elsewhere, please provide links.  I'd like a better 
> understanding as to why the Go team has chosen to explore contracts over 
> other approaches.
>
> Jeff
>

-- 
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] A thought on contracts

2018-09-10 Thread jake6502

Personally, I'm not afraid of writing contracts manually. I suspect that in 
the vast majority of the cases the contract will be clear and pretty 
trivial. In fact, I think it could be a productive part of the design 
process to consider what your generic function minimally needs and write 
the contract first. In some cases it will could in a better implementation. 
If the contract is very complicated it could indicate an overall design 
issue. If the contract is generated after the code is written it could 
result in unnecessary restrictions based on how the code was written. OTOH, 
If the contract is carefully written first, and it turns out that 
implementation requires something more than expected, then that could spur 
some productive thought on the implementation, or the underlying 
assumptions. Either way, IMHO, the result would probably be better code. 

I also think that a tool for updating contracts based on code changes could 
make it easier to  well to update contracts based on code changes. 
Changing a contract to be more restrictive is, by definition a breaking 
change, and a pain point for users of the generic function(s). Making it 
easier to do does not seem like a win to me. 

I'm not strictly against such a tool, but it is worth considering. Only 
time will tell if writing contracts is truly a hard problem, but my gut 
says that, in the end, it will not be that big of an issue. 

Frankly, I'm more concerned with "reading" contracts ... but that's another 
story. 



On Wednesday, September 5, 2018 at 4:57:08 AM UTC-4, Tristan Colgate wrote:
>
> One thing that has been occurring to me on this is that it is probably 
> reasonably practical to have a tool infer and update the contracts. The 
> tool could limit itself to a restricted set of statements, without the spec 
> needing to actually limit them directly.
>
> On Wed, 5 Sep 2018 at 09:17 thwd > 
> wrote:
>
>> If you can't use operations not explicitly stated in a contract: the more 
>> reason to copy-paste a function body into a contract.
>>
>> What I mean by implicit constraints is what the draft calls "implied 
>> constraints".
>>
>> -- 
>> 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: Go’s runtime vs virtual machine

2018-09-04 Thread jake6502
There are a lot of differences, and for the answer to be complete, you 
would need to specify which language you wanted to compare it to. But on a 
really simple level, thwd's answer is more or less correct. A VM language 
is usually compiled into an instruction set for that VM. The VM then 
provides a lot of "special sauce." Go is (usually) compiled directly into 
machine code to be executed directly on the target system. 

One consequence of this is that the executable can be run without having 
any other software installed on the machine. It also  means that the code 
for the stuff you inquired about such as the garbage collector, goroutine 
scheduling and stack management, is all present in the single executable 
compiled by go.

As for learning more, it depends somewhat on what your experience level is, 
and why you want to know. If you are relatively new to programming, I would 
recommend just using go for a while, without worrying too much about the 
"magic."  If you have a strong background already, you could start learning 
about the stuff you mentioned. Garbage collection would be an interesting 
place to start. I don't know of any one resource, but there are a number of 
interesting videos (gophercon, ect) by principal architects on the subject. 
Keep in mind that all these things are constantly evolving, so any 
information you get may not apply to the latest version of the language. 

Good luck.



On Tuesday, September 4, 2018 at 10:50:03 AM UTC-4, thwd wrote:
>
> A virtual machine has its own instruction set. Go compiles to machine code 
> for a given target (which could be a virtual machine).
>
> On Tuesday, September 4, 2018 at 12:27:49 PM UTC+2, Pablo Rozas Larraondo 
> wrote:
>>
>> The Go documentation provides some explanation about the difference 
>> between Go’s runtime and a virtual machine here:
>>
>> https://golang.org/doc/faq#runtime
>>
>> Does anyone can recommend a good place to learn more about this? I’d like 
>> to better understand how Go’s garbage collector, goroutine scheduling and 
>> stack management are handled by the runtime and how it is different from a 
>> virtual machine.
>>
>> Thanks,
>> Pablo
>>
>>

-- 
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: Does fmt.Print* automatically render an error string in as struct (play link)

2018-08-29 Thread jake6502

>
> I can't find anything saying as such

 
  From https://golang.org/pkg/fmt/ : "*4. If an operand implements the 
error interface, the Error method will be invoked to convert the object to 
a string, which will then be formatted as required by the verb (if any).*"

  As mentioned in another reply, Thing has an Error() method, so it " 
implements the error interface."


On Tuesday, August 28, 2018 at 8:15:31 PM UTC-4, Louki Sumirniy wrote:
>
> I discovered quite by accident and now I can't find anything saying as 
> such, but this example
>
> package main
>
> import (
>   "fmt"
>   "errors"
> )
>
> type Thing struct {
>   err error
> }
>
> type thing interface {
>   Error() string
> }
>
> func (t *Thing) Error() string {
>   return t.err.Error()
> }
>
> func main() {
>   t := new(Thing)
>   t.err = errors.New("testing")
>   fmt.Println(t)
> }
>
> https://play.golang.org/p/xBIGIvSZkqO
>
> as you can see by running it, prints the error value inside the struct. 
>
> I am writing a library where I am using a 'pipeline' model so I can string 
> pointer methods together in a chain, which requires putting an error value 
> inside the structure, and then it does this when I print the struct. It's 
> quite handy but unexpected. I assume if a struct satisfies the error 
> interface it calls it to generate the string.
>

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


[go-nuts] Re: Regarding string immutablity

2018-08-28 Thread jake6502
I think Jan answered the question asked. But, do you have some specific 
concern that prompted the question? Is it about security, or memory usage, 
or just curiosity?

On Tuesday, August 28, 2018 at 10:55:27 AM UTC-4, Jay Sharma wrote:
>
> Hi All,
>
> I went through documentation and many post. Every where it is specified 
> *strings 
> are immutable*.
>
> I have some string :
>
> x := "teststring"
>
>
> I want to *wipe out/overwrite* the content of this string x from 
> disk/memory. 
>
> As per me the simplest way to do this:
>
> x = ""
>
>
> or If I want to overwrite it with some new content, I can do this: [*Here 
> length of new string is equal to length of old string*]
>
> x = "new1string"
>
>
> As I am overwriting the content with new content, Is it *inplace 
> replacement* [same memory is being updated] or a new copy will be created 
> with new content and old content will be there in the memory ? 
>
>
>

-- 
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: What is the proper way to delete a key which holding a pointer in a map

2018-08-27 Thread jake6502
Just to be clear, the memory used by the values *are *freed. In your 
example, those are the Person structs. It is only the internal memory used 
by the map that is not freed. See https://play.golang.org/p/fWOIbvjFjyB. In 
that test, the "internal" memory that is not freed is about 14 bytes per 
entry. 

Of course, keep in mind that nothing is freed until a GC is done. 

On Monday, August 27, 2018 at 5:00:14 AM UTC-4, Kasun Vithanage wrote:
>
> I've a map which has set of keys and pointing to some structs like this. 
> In here i allocate lot of entries and trying to delete them. But the memory 
> usage is not shrinking.
>
> According to this issue  it 
> seems how go behave at this point. In there its suggested to create a new 
> map and move all data there for reduced memory usage. But that seems not a 
> better option as it 
> is an expensive operation against such large map.
>
> What is the best way to delete a key from map freeing the memory occupied 
> by the Value(a pointer in this case).
>
> type Person struct {
>Name string
> }
>
> func NewPerson(name string) *Person {
>   return {Name: name}
> }
>
> func main() {
>   m := make(map[int]*Person)
>
> for i := 0; i < 10; i++ {
>   m[i] = NewPerson("Person" + strconv.Itoa(i))
>}
>
> for index := 0; index < 1; index++ {
>   m[index] = nil
>  delete(m, index)
>}
> }
>
>
>
>

-- 
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: Ioctl Syscall with go and c

2018-08-26 Thread jake6502
I was aware that your parameters would not fit the Ioctl functions. As 
Ian pointed out, you would need to use *golang.org/x/sys/unix/Syscall() *and 
friends. 

On Sunday, August 26, 2018 at 10:00:11 AM UTC-4, sbez...@cisco.com wrote:
>
> Hi Jake,
>
>  
>
> Ioctl implementation in unix package seems a bit limited, how do you pass 
> for example a required struct if “func IoctlSetInt(fd int, req uint, value 
> int)” allows only to accept int?? If this package had a func accepting 
> uintptr as a parameter, then I guess that could work.
>
>  
>
> Thank you
>
> Serguei
>
>  
>
>  
>
> *From: *> on behalf of "
> jake...@gmail.com " >
> *Date: *Friday, August 24, 2018 at 12:09 PM
> *To: *golang-nuts >
> *Subject: *[go-nuts] Re: Ioctl Syscall with go and c
>
>  
>
> Probably unrelated to your problem, but IIUC, the syscall package is 
> "deprecated", or "frozen". According to the syscall documentation 
> :
>
> *This package is locked down. Code outside the standard Go repository 
> should be migrated to use the corresponding package in the golang.org/x/sys 
>  repository. That is also where updates required 
> by new systems or versions should be applied. *
>
>  
>
> So, while unlikely, it is possible that is the problem. In any case, 
> unless I misunderstand, the preferred package for you to use is 
> golang.org/x/sys/unix.
>
>  
>
> On Thursday, August 23, 2018 at 7:02:13 AM UTC-4, sbez...@cisco.com 
> wrote: 
>
> Hello, 
>
> I am converting some C code to Go and hit an issue with one particular 
> Syscall: 
>
> In C: 
>
> device = ioctl(group, 0x3b6a, path); 
> where path is char[N] 
>
> In Go: 
> ioctlId := 0x3b6a 
> device, _, errno := syscall.Syscall( 
> syscall.SYS_IOCTL, 
> uintptr(group), 
> uintptr(unsafe.Pointer()), 
> uintptr(unsafe.Pointer(pciDevice)), 
> ) 
> Where pciDevice is *string with exactly the same value as path in C. 
>
> When I run Go bits on the same h/w, same OS, same everything, it fails 
> with "errno 22 (invalid argument)". It seems that the issue is how string 
> gets passed to Syscall, but I could not find any examples how to do it 
> correctly. 
> Appreciate some advice here. 
>
> Thank you 
> Serguei 
>
> -- 
> 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: Ioctl Syscall with go and c

2018-08-24 Thread jake6502
Probably unrelated to your problem, but IIUC, the syscall package is 
"deprecated", or "frozen". According to the syscall documentation 
:

> *This package is locked down. Code outside the standard Go repository 
> should be migrated to use the corresponding package in the golang.org/x/sys 
> repository. That is also where updates required by new systems or versions 
> should be applied. *
>

So, while unlikely, it is possible that is the problem. In any case, unless 
I misunderstand, the preferred package for you to use is 
golang.org/x/sys/unix.

On Thursday, August 23, 2018 at 7:02:13 AM UTC-4, sbez...@cisco.com wrote:
>
> Hello, 
>
> I am converting some C code to Go and hit an issue with one particular 
> Syscall: 
>
> In C: 
>
> device = ioctl(group, 0x3b6a, path); 
> where path is char[N] 
>
> In Go: 
> ioctlId := 0x3b6a 
> device, _, errno := syscall.Syscall( 
> syscall.SYS_IOCTL, 
> uintptr(group), 
> uintptr(unsafe.Pointer()), 
> uintptr(unsafe.Pointer(pciDevice)), 
> ) 
> Where pciDevice is *string with exactly the same value as path in C. 
>
> When I run Go bits on the same h/w, same OS, same everything, it fails 
> with "errno 22 (invalid argument)". It seems that the issue is how string 
> gets passed to Syscall, but I could not find any examples how to do it 
> correctly. 
> Appreciate some advice here. 
>
> Thank you 
> Serguei 
>
>

-- 
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: Ioctl Syscall with go and c

2018-08-23 Thread jake6502
First off, I don't know how you are posting your code samples, but they are 
unreadable in my Firefox and Chrome on windows. 

Second, I would point out that the system you use for converting a "string" 
to the buffer will fail if there are any non-ascii characters. 

Third, OT, but I wonder why pciDevice is a string pointer, instead of a 
string?

Personally, I don't see anything *decisively *incorrect, but there is a lot 
of context that is missing. If you wanted to indicate your OS, and provide 
a complete working sample, I'm sure I, or someone else could help more. 

One thing that jumps out at me is the use of  
*uintptr(unsafe.Pointer())*, in your initial example. It is hidden 
by the function  *VFIO_GROUP_GET_DEVICE_FD()*, which is not provided, in 
your larger example. Are you sure you want the pointer to that value, and 
not the actual value? Maybe *uintptr(ioctlId))* instead. Seems more 
standard for IOCTL to me. 

And, of course the changes you made to create an appropriate string buffer 
are necessary.


On Thursday, August 23, 2018 at 11:47:18 AM UTC-4, sbez...@cisco.com wrote:
>
> Hi Max,
>
>  
>
> Thanks for the suggestion, unfortunately it did not help, see below:
>
>  
>
> func GetGroupFD(group int, pciDevice *string) (int, error) {
>
> fmt.Printf("VFIO_GROUP_GET_DEVICE_FD() returned: %04x\n", 
> VFIO_GROUP_GET_DEVICE_FD())
>
> buffer := make([]byte, len(*pciDevice)+1)
>
> for i, c := range *pciDevice {
>
> buffer[i] = uint8(c)
>
> }
>
> buffer[len(*pciDevice)] = 0x0
>
> fmt.Printf("pciDevice: %s\n", string(buffer))
>
> device, _, errno := syscall.Syscall(
>
> syscall.SYS_IOCTL,
>
> uintptr(group),
>
> uintptr(VFIO_GROUP_GET_DEVICE_FD()),
>
> uintptr(unsafe.Pointer([0])),
>
> )
>
> if errno != 0 {
>
> return 0, fmt.Errorf("fail to get file descriptor for %d with 
> errno: %+v", group, errno)
>
> }
>
> return int(device), nil
>
> }
>
>  
>
> Any other suggestions?
>
> Thank you
>
> Serguei
>
>  
>
> *From: *> on behalf of Max <
> massimilia...@gmail.com >
> *Date: *Thursday, August 23, 2018 at 10:46 AM
> *To: *golang-nuts >
> *Subject: *Re: [go-nuts] Re: Ioctl Syscall with go and c
>
>  
>
> Hi Serguei,
>
>  
>
> a Go string or *string do not correspond to a C char *
>
> You must pass the address of the first byte of a sufficiently large buffer:
>
>  
>
> func GetGroupFD(group int, pciDevice *string) (int, error) {
>
>   const N = 256
>
>   var buffer [N]byte
>
>   device, _, errno := syscall.Syscall(
> syscall.SYS_IOCTL,
> uintptr(group),
> uintptr(unsafe.Pointer()),
> [0],
> )
>
>/* if ioctl() is successful, find '\0' in buffer[] and copy the 
> relevant portion in *pciDevice */
>
> }
>
>
> On Thursday, August 23, 2018 at 2:55:29 PM UTC+2, sbez...@cisco.com 
> wrote: 
>
> I changed code a little bit to be able to examine variables:
>
>  
>
>  func GetGroupFD(group int, pciDevice *string) (int, error) {
>
> ioctlId := 0x3b6a 
>
> var buffer uintptr
>
> buffer = uintptr(unsafe.Pointer(pciDevice))
>
>  
>
> -- 
> 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: Decoding the buffer to a struct sent from C program

2018-08-16 Thread jake6502
Perhaps someone can spot the error just by looking at your code. But a 
couple of tips that will help others help you. 

1. Specify what exactly the "failure" is. What output do you get?
2. Include the log output for a sample run.
3. Print, and include a sample value of "data" (the binary data from 
ReadErrorMsg) so other can run and reproduce the problem.
4. You should not be discarding the error from binary.Read. Always check 
your errors. If there is one, then handle it, or at least log it to help 
diagnose the problem. 

Good luck. 


On Wednesday, August 15, 2018 at 11:29:44 PM UTC-4, naveen.b@gmail.com 
wrote:
>
> Hi All, 
>
> I am learning golang and in the process i am trying to decode the buffer 
> sent from a C client to a structure in golang. 
> however that fails , please guide me through the process. The 
> communication uses UNIX domain socket, between a c program and a 
> golang process.
>
> C structure.
> struct error_notify_msg_t {
> int type;
>
> char str[384];
>
> char name[64];
>
> char id[256];
>
> char ip[60];
> }
>
> Golang Structure.
>
> type ErrorNotifyMsg struct {
> //Type ...
> Type uint32
> //Str ...
> Str [384]string
> //Name ...
> Name [64]string
> //ID ...
> ID [256]string
> //Ip ...
> IP [60]string
> }
>
> func ReadErrorMsg() {
> //var n int
> buf := make([]byte, 1024)
> for {
>
> n, err := ConnErr.Read(buf[:])
> if err != nil {
> return
> }
> data := buf[0:n]
> Log.InfoS("DecodeErrorMsg", log.KV{"Bytes read :": n})
> msg, err := DecodeErrorMsg(data)
> if msg != nil {
> ErrNotify <- *msg
> }
> }
> }
>
> var ourEnd = binary.LittleEndian
>
> func DecodeErrorMsg(val []byte) ErrorNotifyMsg {
> ntfy := ErrorNotifyMsg{}
> buf := bytes.NewBuffer(val)
> buf.Next(1)
> _ = binary.Read(buf, ourEnd, )
> Log.InfoS("DecodeErrorMsg", log.KV{"ntfy.Type": ntfy.Type})
> buf.Next(384)
> _ = binary.Read(buf, ourEnd, )
> Log.InfoS("DecodeErrorMsg", log.KV{"ntfy.Str": ntfy.Str})
> buf.Next(64)
> _ = binary.Read(buf, ourEnd, )
> Log.InfoS("DecodeErrorMsg", log.KV{"ntfy.Name": ntfy.Name})
> buf.Next(256)
> _ = binary.Read(buf, ourEnd, )
> Log.InfoS("DecodeErrorMsg", log.KV{"ntfy.ID": ntfy.ID})
> buf.Next(60)
> _ = binary.Read(buf, ourEnd, )
> Log.InfoS("DecodeErrorMsg", log.KV{"ntfy.IP": ntfy.IP})
> return ntfy
> }
>
> Thanks,
> Naveen
>
>

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


[go-nuts] Re: Go modules and semver question

2018-08-15 Thread jake6502
The initial premise was that the API and "Behavior" have not changed. What 
this means for the literal API is pretty clear - that public function 
signatures and such are unchanged. "Behavior" is a bit more tricky and 
subjective. If you define "behavior" is the strictest possible sense, then 
there is pretty much no such thing as a patch. But, for these purposes, I 
would define "behavior" as the contracted behavior. This is why proper 
documentation for the package as a whole, and any public functions, globals 
and constants is so critical. 

So back to your example. If the package makes no specific guarantees about 
the internal format of the resulting PDF, aside from its correctness, then 
is is a patch release. It is generally considered bad form for a user of a 
package to rely on undocumented internals like this. It is the very 
definition of fragility. Many a fragile program has broken because it 
assumed things about the exact formatting of JSON, or XML, or even the text 
of an error message.   

If, on the other hand, the documentation has made specific guarantees which 
will now be broken about the internal form of the PDF, then that, sadly, 
means a major version change. This, again, is why it is so important that 
package creators think very carefully about what they do, and don't promise 
in documentation. 

On Wednesday, August 15, 2018 at 11:05:01 AM UTC-4, meta keule wrote:
>
>
> I am not thinking of a certain package.
>
> The singleton problem is just one example. 
> I'll give you another one:
>
> Let's say my library is a porcelain lib for creating PDFs,
> that is using under the hood anthoer library that does 
> the real work.
>
> So some of the resulting PDF files look different after the update, 
> although
> that difference come only from the underlying change of the core lib.
>
> I can think of lots of variations on this theme. You might say: "It 
> depends...",
> but then with a large project it might take a lot of time to go through 
> all these
> changes and decide, if one would rate them as a breaking change.
>
> So it boils down to: Am I reponsible for the upstream breakages, if I 
> "pass them through"
> and if not: isn't it a false security to believe in semantic versioning 
> then?
>

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


[go-nuts] Re: `go test -c` skips init from main while `go test` doesn't

2018-08-14 Thread jake6502
I am unable to reproduce using a small test app on either Windows or 
Ubuntu, using go 1.10.3. In all cases the init() function in main is run 
when the test binary is run. Perhaps you could provide a minimal 
reproducible example?

On Monday, August 13, 2018 at 8:21:30 PM UTC-4, Gert wrote:
>
> Hi, `go test` runs the main init but the binary created by 
>
> go test -c -a -tags 'netgo noplugin' -gcflags "all=-N -l"
>
> doesn't. Is this a bug? Also it's seems you can't compile static test 
> binaries only non test binaries can be compiled static?
>

-- 
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: Examples testing with two newline, but only one newline

2018-08-13 Thread jake6502
Looks like a bug to me. I would suggest you open an issue.

It is not clear to me what the intended behavior is. It is documented that 
examples strip some white space when comparing output. So it may be 
intentional that multiple white space lines are removed from the expected 
output. In that case, IMO, the bug is that the same transformation is not 
applied to the output before comparing. Conversely, it is possible that the 
removal of the blank lines is the bug. 

That said, since examples are documented to "strip white space", I would 
remind you to also write actual tests, if the white space of the results 
matters to you. 


On Saturday, August 11, 2018 at 4:10:04 AM UTC-4, 子風 wrote:
>
> Hi
>
> https://play.golang.org/p/AIB-yJaExVu
>
> When I want to use examples to test my code, I find something odd.
> Example1 could pass, but Example2 failed
>
> --- FAIL: Example2 (0.00s)
>> got:
>> hello
>> .
>>
>> 123
>> want:
>> hello
>> .
>> 123
>> FAIL
>> exit status 1
>
>
> It seems Examples could only show one newline.
> Is there a solution to solve it? 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: How should I avoid - literal copies lock value from

2018-08-11 Thread jake6502
I don't see anything fundamentally wrong with using a *sync.Mutex as long 
as users always use New(). It allows Set to be passed by value, which is 
nice. 

But if you keep the mutex as a non pointer, then you probably want to pass 
a slice of set pointers:
func (set *Set) Diff(sets []*Set) *Set
This avoids copying the mutex when you create your slice, so the test line 
becomes:
set1.Diff([]*Set{set2, set3})

Of course your original Diff code is technically ok. The problem is in 
creating a []Set from individual Set objects without violating the mutex 
copy rules is difficult, and would require a bunch of code. 


On Friday, August 10, 2018 at 3:02:57 AM UTC-4, Kasun Vithanage wrote:
>
> I want an slice of sets
>
> On Tuesday, August 7, 2018 at 6:32:25 PM UTC+5:30, Dave Cheney wrote:
>>
>> Pass a pointer, *Set into your Diff method. 
>
>

-- 
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: What is rationale behind slices cannot be compared to each other with == ?

2018-08-02 Thread jake6502
A previous discussion of this was quite long (89 posts) - maybe start 
there: https://groups.google.com/d/msg/golang-nuts/ajXzEM6lqJI/wbTPh2TmAwAJ

On Thursday, August 2, 2018 at 1:21:15 PM UTC-4, Andrey Tcherepanov wrote:
>
> The following code does not compile. What was *rationale* behind slices 
> being excluded from being nicely comparable by == like anything else ?
>
> package main
>
> import (
> "fmt"
> )
>
> func main() {
> var a, b []byte
>
> fmt.Println("equals?", a == b)
> }
>
> Slices are _excluded_ from deep comparison by stating "Other values - 
> numbers, bools, strings, and channels - are deeply equal if they are equal 
> using Go's == operator." (from documentation of reflect.DeepEqual() 
>  ).
>
>
> Sorry if it is FAQ of some sort, but I seems cannot find an answer to 
> "why".
>
> Thank you very much,
>   Andrey
>
>

-- 
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] stdatomic.h, cgo, and sync/atomic

2018-08-02 Thread jake6502
On Wednesday, August 1, 2018 at 10:17:38 AM UTC-4, Ian Lance Taylor wrote:
>
> [...]
> That said, the exact semantics of the sync/atomic operations are not 
> written down (that is https://golang.org/issue/5045). 
>
 
I really love go, but this is one thing that has annoyed me for years. This 
issue is from 2013, and AFAICT, there is still no clear statement of what 
guarantees the sync/atomic functions make. I know that they should be 
rarely used. I know that the edge cases for atomic operations are 
complicated to define, hence all the options for C++ atomics. But on the 
rare occasion that I do need to use them, I always feel a lot of 
trepidation, because I can really make few, if any guarantees based on the 
documentation.   


-- 
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: Counting semaphore vs Workerpool

2018-05-26 Thread jake6502
So, it looks to me like 1 million URLS will spin up 1 million goroutines. 
That seems unnecessary, and likely to be a problem. I usually default to 
the simplest model, unless there is a reason to do otherwise. IMHO, here 
that would be to spin up as many goroutines as you want to be working at 
once (500), then feed data through a channel. Untested pseudo-code:
func fetchAll(ctx context.Context) {
workerCount := min(500, len(urls))
c := make(chan string)

// Spin up workers
for i := 0; i < workerCount; i++ {
go doWork(ctx, c)
}
// Feed them work
for _, u := range urls {
if u == "" {
continue
}
_, err := url.Parse(u)
if err != nil {
log.Printf("%s returned an error- %v", u, err)
continue
}
c <- u
}
// All work sent, signal workers to die. Note, workers may still be
// processing at this point.
close(c)
}

func doWork(ctx context.Context, c chan string) {
for {
u := <-c
if u == "" {
// channel was closed ... no more work.
return
}
fetch(ctx, u)
}
}

func fetch(ctx context.Context, u string) {
req, err := http.NewRequest(http.MethodGet, u, nil)
if err != nil {
log.Printf("%s returned an error while creating a request- %v", u, 
err)
return
}
req = req.WithContext(ctx)
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("%s returned an error while performing a request  - %v", 
u, err)
return
}
//Close response body as soon as function returns to prevent resource
//leakage. https://golang.org/pkg/net/http/#Response
defer res.Body.Close()
}

I find this basic model simple and easy top reason about. And it should 
avoid wasted goroutines. I have not really paid much attention to "fetch". 
I assume it was already correct code. I'm not sure if you are expecting to 
handle a cancel on the Context. If so, then you will want to add a check 
for that in your main fetchAll() loop, and bail early if it was canceled. 


On Saturday, May 26, 2018 at 11:48:28 AM UTC-4, Karthik Rao wrote:
>
> I am writing an application that has to fetch data from - say a million 
> URLs. I currently have an implementation which looks like the code below 
>
> //Make sure that we just have 500 or less goroutines fetching from URLs
> sem := make(chan struct{}, min(500, len(urls)))
> //Check if all URLs in the request are valid and if so spawn a goroutine 
> to fetch data.
> for _, u := range urls {
> _, err := url.Parse(u)
> if err != nil {
> log.Printf("%s returned an error- %v", u, err)
> continue
> }
> go fetch(ctx, sem, u)
> }
>
> func fetch(ctx context.Context, sem chan struct{}, u string) {
> sem <- struct{}{}
> defer func() { <-sem }()
> req, err := http.NewRequest(http.MethodGet, u, nil)
> if err != nil {
> log.Printf("%s returned an error while creating a request- %v", u, err)
> return
> }
> req = req.WithContext(ctx)
> res, err := http.DefaultClient.Do(req)
> if err != nil {
> log.Printf("%s returned an error while performing a request  - %v", u, err)
> return
> }
> //Close response body as soon as function returns to prevent resource 
> lekage.
> //https://golang.org/pkg/net/http/#Response
> defer res.Body.Close()
> }
>
> Would this application choke when a million goroutines are spawned and are 
> waiting for a place on the sem channel?  I have profiled my code using 
> pprof and see no problems when I tested it with 50k URLs.
>
> What is the cost of a goroutine waiting on the semaphore channel? Would it 
> be ~2KB?
>
> Is using a worker pool like the one mentioned here 
> 
>  better? 
> What would be the advantages? I am of the opinion that the runtime 
> scheduler is a better judge when it comes to managing goroutines.
>
> Another question is - Would it be better that acquire the semaphore within 
> the loop such that I limit the number of goroutines spawned? Mr Dave Cheney 
> suggested otherwise in his talk here 
> .
>
> Any other suggestions are also welcome.
>
> TIA!
>

-- 
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: Freeing memory of a cgo library

2018-05-26 Thread jake6502
FYI, the standard way around this is to expose a "free" method from your 
DLL for memory allocated by the DLL. The other way is to require that users 
of the DLL supply the memory in advance to functions needing it. These two 
methods are the ones used by the Windows libraries themselves. Pretty 
standard stuff. One other possibility might be to register some sort of 
callback from the C++ code that the go DLL code can call to allocate memory 
from the C++ space. But I would not prefer that. 

Good Luck. 

On Friday, May 25, 2018 at 2:35:19 PM UTC-4, Liron Levy wrote:
>
> Gotcha :)
>
> Thanks for the info, guess i will have to find a way around it then. At 
> least i now know there is no real way to do what i wanted so that close 
> this door :)
>

-- 
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: Freeing memory of a cgo library

2018-05-25 Thread jake6502
Looks like you are on windows. I have worked a lot with windows, C/C++ and 
go, but never actually built a go dll. But, since no one else has picked 
this up, maybe I can help. 

1. I'm not sure what "the cgo" library means here? Do you have this: 
cpp<->go(dll)<->c(cgo)? Or something else. 

2. How is the memory in question allocated? What is the line of code that 
allocates it, and where does it reside in the chain above?



On Thursday, May 24, 2018 at 8:35:07 AM UTC-4, Liron Levy wrote:
>
> Hey guys,
>
> I'm in a bit of a mass, I can not see how I'm getting out of...
> What do I got:
> * A library I built using cgo.
> * A cpp app using this library (dll).
>
> What do I do:
> I try to free memory I have allocated in the cgo library in the cpp app.
>
> What Tools do I use:
> To build the library (dll) I use cgo, then creating a stub lib using the 
> VS cmd. 
> I use visual studio 2017 to compile the app (with /MD) option.
>
> What do I get:
> Critical error detected c374
>
> As far as I can see, this is a result of me freeing data which was 
> allocated in the dll libarary.
> I will note that this does not happen if I create a test app and compile 
> it with gcc.
>
> Unfortunately, I can not avoid using VS as I am working with some CUDA 
> stuff which like VS better :/
>
> Thanks for taking the time to read\help,
> Liron
>  
>

-- 
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: An issue with the select statement.

2018-05-11 Thread jake6502
As others on this thread have pointed out, this use case does not actually 
require select where the cases are checked in order. 

However, for completeness, if you need to check two channels, and they must 
be checked in order, then use two select statements with defaults:
for {
select {
case wi := <-work_ch:
self.do_the_work(wi)
default:
}
select {
case <-self.idle_request:
self.idle_response <- true
default:
}
}

 Again, this should rarely be necessary, or even useful. But there it is.


On Friday, May 4, 2018 at 10:24:56 AM UTC-4, Andriy Pylypenko wrote:
>
> Hi,
>
> I have a scenario which I haven't found a way to implement with the Go 
> channels and select statement while it's no problem to do it with the 
> select()/poll() functions. The scenario is as follows.
>
> Let me use a Go-like pseudo-code to demonstrate the idea. There is a 
> source of a work items which are processed by several goroutines. Here is 
> the source procedure:
>
> work_ch := make(chan *WorkItem)
>
> for {
> work_ch <- NewWorkItem()
> }
>
> And here is the worker thread:
>
> for {
> wi := <-work_ch
> self.do_the_work(wi)
> }
>
> Now I need to suspend the work. I stop supplying the work items and want 
> to make sure the worker goroutines are done with the work. The source 
> procedure becomes something like this:
>
> for {
> if suspend_requested {
> for _, worker := range workers {
> worker.idle_request <- true
> }
> for _, worker := range workers {
> <-worker.idle_response
> }
> report_suspend_is_success()
> wait_until_unsuspended()
> }
> work_ch <- NewWorkItem()
> }
>
> And I want to modify the worker thread like this:
>
> for {
> select {
> case wi := <- work_ch:
> self.do_the_work(wi)
> case <-self.idle_request:
> self.idle_response <- true
> }
> }
>
> However this last snippet of code does not work because the cases within 
> the select statement are randomly chosen when both channels are ready so I 
> have no guarantee that the first case is executed first.
>
> Talking about the select() or poll() functions from the C library which 
> evidently were an inspiration for the Go select statement, there is no 
> problem with the described approach. It's because the select() function 
> returns a complete information about the state of all the monitored 
> descriptors and allows the programmer to decide what he wants to read or 
> write and in which order, based on readiness of every descriptor.
>
> I think it would be a great idea to have some function similar to 
> select()/poll() but working with the Go channels.
>

-- 
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: On Accepting Interfaces and Structs

2018-04-26 Thread jake6502
The example gives me a better understanding of what you are doing, though 
still not much understanding as to *why *you are doing it this way. 
Usually, if I feel that code has a "smell" in Go, there is a way to rethink 
the basic design resulting more "natural" code. But without a full 
understanding of the real situation, it is impossible to say if that 
applies here. But lets assume for now that you must have multiple packages 
that all contain functions that return a common struct.
 

> But I do not like:
>
>
>1. Having a package just to hold a single type,
>
> Personally, I don't see anything inherently wrong with this. If you *must 
*multiple packages that all need the type, then it should be in a package 
separate from those. In many cases there would be functions that could also 
go in package `state`, but if not, then that's ok too.

2. The consumer package is accepting a concrete type and depends on it - 
> seems this one can not be avoided since there is nothing like structural 
> typing for structs in Go.
>

Your example does feel a bit awkward, but, again, I don't have enough 
information on what is really being achieved to suggest a completely 
different model.  

But I will take a shot in the dark. Think interfaces? Perhaps the 
state.State type returned by Clone() could be an interface? This does not 
solve the problem of having to define the interface in a separate package, 
and I would only use an interface if there was a compelling reason to do 
so. 

Taking a further leap,why "Clone()" at all? What do you do with state.State 
in package consumer? Does it have to be a struct for some reason? If you 
could define a set of functionality that a consumer needs from state.State, 
you could then have Concrete1, Concrete2, and Concrete3 all implement that 
functionality. Then consumer can just use them directly as interfaces ... 
or perhaps that is using them indirectly. Anyway, I hope that is somewhat 
comprehensible. 

Good Luck
 - Jake

On Tuesday, April 24, 2018 at 1:49:45 AM UTC-4, Kaveh Shahbazian wrote:
>
> @Jake @Bryan Thanks!
>
> Current solution I use:
>
> A package that holds the shared data type State:
>
> package state
>
> type State struct {
> Latitude  float64
> Longitude float64
> Mark  string
> Name  string
> // ...
> }
>
> Three packages with different implementations and algorithms:
>
> package concrete1
>
> import (
> "gitlab.com/dc0d/gist/2018/Q1/draft/cmd/draft/state"
> )
>
> type Concrete1 struct{}
>
> func (c *Concrete1) Clone() (*state.State, error) { panic("N/A") }
>
> And:
>
> package concrete2
>
> import (
> "gitlab.com/dc0d/gist/2018/Q1/draft/cmd/draft/state"
> )
>
> type Concrete2 struct{}
>
> func (c *Concrete2) Clone() (*state.State, error) { panic("N/A") }
>
> And:
>
> package concrete3
>
> import (
> "gitlab.com/dc0d/gist/2018/Q1/draft/cmd/draft/state"
> )
>
> type Concrete3 struct{}
>
> func (c *Concrete3) Clone() (*state.State, error) { panic("N/A") }
>
> And the consumer package, which will be given a concrete implementation 
> based on some logic (this is where "Accepting interfaces" is happening):
>
> package consumer
>
> import (
> "gitlab.com/dc0d/gist/2018/Q1/draft/cmd/draft/state"
> )
>
> func Use(cln cloner) {}
>
> type cloner interface {
> Clone() (*state.State, error)
> }
>
> The part in question is the *state.State data type. This is the best I 
> could come up with.
>
> But I do not like:
>
>
>1. Having a package just to hold a single type,
>2. The consumer package is accepting a concrete type and depends on it 
>- seems this one can not be avoided since there is nothing like structural 
>typing for structs in Go.
>
>
> There might be a better way to do this.
>

-- 
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: On Accepting Interfaces and Structs

2018-04-23 Thread jake6502
My gut feeling is that there is an elegant way to achieve what you want. 
Unfortunately, I am having trouble following the code you are describing, 
and more importantly,  what you are actually trying to accomplish. Perhaps 
it is my failing.

If you would post a more complete example, showing the relevant code in all 
the related packages, I suspect you would get constructive suggestions.

- Jake


On Saturday, April 21, 2018 at 7:51:55 AM UTC-4, Kaveh Shahbazian wrote:
>
> Regarding "Accept interfaces, return concrete types", how can it be 
> applied for structs that represent a payload/value?
>
> For example in package first, logger is defined as:
>
> type logger interface {
> Debugf(template string, args ...interface{})
> Errorf(template string, args ...interface{})
> Infof(template string, args ...interface{})
> }
>
> And package first only accepts a logger that implements the logger 
> interface.
>
> Now lets assume there is a need for passing a struct too, like some config 
> or state.
>
> This causes importing the original package that, that config or state 
> struct resides in; while package first is happily accepting other things 
> from that package using interfaces.
>
> For example in package second there is some tool that is represented using 
> this interface in package first:
>
> type cloner interface {
> Clone() (*second.State, error)
> }
>
>
> As it can be seen, now package first has to explicitly import package 
> second, because of the type *second.State.
>
> Currently I break things by renaming the second package to something 
> meaningless when importing like:
>
> type cloner interface {
> Clone() (*p2nd.State, error)
> }
>
> But this is not really a work around and package second leaks into the 
> scope of package first anyway.
>
> Is there a way to actually achieve this?
>

-- 
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] Extension for type assertion of interface array

2018-04-19 Thread jake6502
Yes, to use the functions above you will need to copy the slices of 
landSpaceto slices of the respective interface types. But I you do not need 
to do any type assertions. Like this: 

https://play.golang.org/p/eFTUqpImyPc
package main

import (
"fmt"
)

type landSpace struct{}

func (*landSpace) Foo() {
fmt.Println("Foo")
}

func (*landSpace) Bar() {
fmt.Println("Bar")
}

type Shape interface {
Foo()
}

type Property interface {
Bar()
}

var a []*landSpace

func processShapes(shapes []Shape) {
for _, s := range shapes {
s.Foo()
}
}

func evaluateProperties(properties []Property) {
for _, p := range properties {
p.Bar()
}
}

func main() {
a = append(a, {}, {})

var shapes []Shape
for _, l := range a {
shapes = append(shapes, l)
}
processShapes(shapes)

var properties []Property
for _, l := range a {
properties = append(properties, l)
}
evaluateProperties(properties)
fmt.Println("Hello, playground")
}

Is this what you meant? I see how something like shapes = a.([]Shape) would 
be convenient to avoid having to do an explicit conversion. Hoever, until 
Go has some form of generics,  it seems unlikely. Keep in mind that a Shape and 
*landSpace are two different types, with different in memory 
representations. So to avoid major language changes, the type assertion 
would have to create a new slice anyway.


On Thursday, April 19, 2018 at 12:59:12 AM UTC-4, Sakthi Natesan wrote:
>
> Usescases that I came across doesn't involve []interface{}. 
>
> My usecases will be similar to this sample code 
> 
>
> type landSpace struct {
> //consider that landSpace implements all functions from both Shape and 
> property interfaces
> ...
> }
> type Shape interface {
> ...
> }
>
>
> type property interface {
>
> ...
> }
>
>
> var a []*landSpace
>
> func processShapes(shapes []Shape) {
> //
> }
>
> func evaluateProperties(properties []Property) {
> //
> }
>
>
>
> If I want to pass the variable 'a' to both the functions, then I have to 
> write two functions to clone and typeAssert to respective interfaces.
>
>
> On Wednesday, 18 April 2018 19:53:33 UTC+5:30, Jan Mercl wrote:
>>
>> On Wed, Apr 18, 2018 at 4:13 PM  wrote:
>>
>> When possible, avoid using '[]interface{}' and use just 'interface{}' 
>> instead: https://play.golang.org/p/oPtPoGChkMZ.
>>
>>
>> -- 
>>
>> -j
>>
>

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


Re: [go-nuts] sync.Cond implementation

2018-04-16 Thread jake6502
On Monday, April 16, 2018 at 7:08:27 AM UTC-4, Jesper Louis Andersen wrote:
>
> On Sat, Apr 14, 2018 at 7:02 PM Penguin Enormous  > wrote:
>
>> But looking at your answer, I see that you may imply certain race 
>> conditions are allowed. Could you explain a bit more on that? Aren't race 
>> conditions supposedly bad?
>>
>> Race conditions can, in certain cases, be benign if guarded properly by 
> some other code. As long as you eventually solve the race in a valid way. 
>

A little OT, but to avoid confusion for other readers, I want to point out 
that "logic race conditions" can be benign, but that "data race conditions" 
should never be considered benign *in user code*. By a "data race 
condition", I mean that two threads (or goroutines) are accessing the same 
data at the same time, and one of the accesses is a write.

I am not trying to imply that Jesper was saying any different. I just 
wanted to clarify for others who could misinterpret his comments.

-- 
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: Scheduler discrepancy between Linux and OS X with Gosched()

2018-04-03 Thread jake6502
For what it is worth, when I run your new code (without channels) on 
windows it takes consistently 1 second. On Linux it takes variably between 
400ms and 1.5 seconds. Both running go 1.10. But, on my systems, this seems 
to be actually measuring time.Sleep(). Removing the call to spin() and the 
second runtime.Gosched() results in the same times:

package main

import (
"log"
"runtime"
"time"
)

func main() {
runtime.GOMAXPROCS(1)

t0 := time.Now()
for i := 0; i < 1000; i++ {
time.Sleep(1 * time.Microsecond)
}

log.Printf("Finished in %v.", time.Since(t0))
}

I can not speak for your original example, but in this one I would be 
looking to time.Sleep(). 

- Jake


On Tuesday, April 3, 2018 at 2:12:40 PM UTC-4, brianbl...@gmail.com wrote:
>
> Hi Dave, thanks for the reply!
>
> It makes sense that the send c <- 0 is not guaranteed to transfer control 
> to the receiving goroutine. But is it not guaranteed that runtime.Gosched() 
> will at least check if another goroutine is runnable? I thought that was 
> roughly the point of runtime.Gosched(). 
>
> I see what you're saying in that when the second goroutine calls Gosched, 
> the sleep period may not be finished. But this will only waste another 100 
> microseconds by design (not 100 milliseconds), so it seems like control 
> flow should return to the main goroutine approximately when the sleep call 
> finishes.
>
> I created a simpler example, that doesn't use channels and avoids the work 
> length ambiguity, posted below. Now the secondary goroutine just does an 
> infinite loop of runtime.Gosched(). It should be instantaneous to run (and 
> is on my Mac), but it takes almost exactly 5 seconds on Ubuntu, suggesting 
> that there is some fixed 5 millisecond delay on Gosched(). And adding a 
> print above spin's Gosched makes it instantaneous.
>
> Thanks for your patience! I'm working on an application where the ~5ms 
> Gosched delay is meaningful and I am very curious to figure out what's 
> going on here. 
> package main
>
> import (
> "log"
> "runtime"
> "time"
> )
>
> func spin() {
> for {
> runtime.Gosched()
> }
> }
>
> func main() {
> runtime.GOMAXPROCS(1)
> go spin()
>
> t0 := time.Now()
> for i := 0; i < 1000; i++ {
> time.Sleep(10 * time.Microsecond)
>
> runtime.Gosched()
> }
>
> log.Printf("Finished in %v.", time.Since(t0))
> }
>
>
> On Tuesday, April 3, 2018 at 12:56:49 AM UTC-4, brianbl...@gmail.com 
> wrote:
>>
>> I've run into some mysterious behavior, where Gosched() works as expected 
>> in Mac OS X, but only works as expected in Ubuntu if I put a logging 
>> statement before it.
>>
>> I originally posted this on Stack Overflow but was directed here. Post: 
>> https://stackoverflow.com/questions/49617451/golang-scheduler-mystery-linux-vs-mac-os-x
>>
>> Any help would be greatly appreciated! Very curious what's going on here, 
>> as this behavior came up while I was trying to write a websocket broadcast 
>> server. Here's a minimal setup that reproduces the behavior:
>>
>> The main goroutine sleeps for 1000 periods of 1ms, and after each sleep 
>> pushes a dummy message onto another goroutine via a channel. The second 
>> goroutine listens for new messages, and every time it gets one it does 10ms 
>> of work. So without any runtime.Gosched() calls, the program will take 
>> 10 seconds to run.
>>
>> When I add periodic runtime.Gosched() calls in the second goroutine, as 
>> expected the program runtime shrinks down to 1 second on my Mac. However, 
>> when I try running the same program on Ubuntu, it still takes 10 seconds. I 
>> made sure to set runtime.GOMAXPROCS(1) in both cases.
>>
>> Here's where it gets really strange: if I just add a logging statement 
>> before the the runtime.Gosched() calls, then suddenly the program runs 
>> in the expected 1 second on Ubuntu as well.
>>
>>
>> package main
>> import (
>> "time"
>> "log"
>> "runtime")
>>
>> func doWork(c chan int) {
>> for {
>> <-c
>>
>> // This outer loop will take ~10ms.
>> for j := 0; j < 100 ; j++ {
>> // The following block of CPU work takes ~100 microseconds
>> for i := 0; i < 30; i++ {
>> _ = i * 17
>> }
>> // Somehow this print statement saves the day in Ubuntu
>> log.Printf("donkey")
>> runtime.Gosched()
>> }
>> }}
>>
>> func main() {
>> runtime.GOMAXPROCS(1)
>> c := make(chan int, 1000)
>> go doWork(c)
>>
>> start := time.Now().UnixNano()
>> for i := 0; i < 1000; i++ {
>> time.Sleep(1 * time.Millisecond)
>>
>> // Queue up 10ms of work in the other goroutine, which will backlog
>> // this goroutine without runtime.Gosched() calls.
>> c <- 0
>> }
>>
>> // Whole program should take about 1 second to run if the Gosched() 
>> calls 
>> // work, otherwise 10 seconds.
>> 

[go-nuts] Re: About a channel detail, bug, defect, or intended?

2018-03-24 Thread jake6502
There may not be any guarantee that the channel will always be full, but in 
practice your code always produces 100 results for me. Both in the 
playground , and on my machine  (go 
version go1.10 windows/amd64). With or without the Sleep commented out. Am 
I missing something?

- Jake

On Saturday, March 24, 2018 at 6:41:19 AM UTC-4, T L wrote:
>
> In the following example, there are 99 goroutines queuing and blocking on 
> sending a value to c.
> When the only buffered value is received, it looks there is a time 
> interval until the buffer is filled.
> Shouldn't it be that the receive from the only buffer and fill next 
> queuing value to the only buffer in one atomic operation?
>
>
> package main
>
> import "time"
>
> func main() {
> c := make(chan int, 1)
> for i := 0; i < 100; i++ {
> go func() {
> c <- 1
> }()
> }
> 
> time.Sleep(time.Second)
> 
> n := 0
> for len(c) == cap(c) {
> <-c
> println(n, len(c)) // here, len(c) is always 0
> n++
> // time.Sleep(time.Second/1000) // if this line is not commented 
> off, there will be 100 lines output.
> }
> }
>

-- 
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: Long running task in select case

2018-03-17 Thread jake6502


On Saturday, March 17, 2018 at 10:37:48 AM UTC-4, matthe...@gmail.com wrote:
>
> I think the second example alternative given (playground link above) has a 
>> data race?
>
>
> I’m not surprised that the race detector sees something (a read can happen 
> during a write of the checked bool) but I don’t think this could actually 
> cause problems because the var’s memory value will always be 0 or 1.
>

> There may be implementation details or future implementation details that 
> cause a problem though, so one option could be to protect the bool as a 
> shared resource with a mutex or equivalent, but I think rog’s solution is 
> better anyway (the first one).
>
 
+1. At this point, I would like to pull out the classic blog post: Benign 
data races: what could possibly go wrong? 

 
I would put this in the list of articles every programmer should read. In 
part because it is so very tempting to cut corners when you "know that it 
will work". And it may, on your architecture, with the current compiler. 
But even if it does it could silently break later.

There is no such thing as a safe race in user code. 

Respect
  - Jake  

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


[go-nuts] Re: confusing a lock demo about https://golang.org/ref/mem#tmp_8

2018-03-13 Thread jake6502
I would like to point out that the example code you refer to is meant to 
illustrate a specific behavior of locks. It is *not* necessarily intended 
to be an example of good style. As a "new gopher" I would avoid this idiom. 
If you did use this, some significant commenting would be needed. 

Also, what blog post are you referring to?

- Jake

On Tuesday, March 13, 2018 at 9:27:08 AM UTC-4, 郎凯 wrote:
>
> var l sync.Mutex
> var a string
>
> func f() {
> a = "hello, world"
> l.Unlock()
> }
>
> func main() {
> l.Lock()
> go f()
> l.Lock()
> print(a)
> }
>
> I'm a new gopher, reading a blog about lock and having a problem, in 
> general , we use sync.Mutex in pairs, in the above code why could it call 
> lock two times  in main.
> Any help is Appreciated.
> Thanks in advanced.
>

-- 
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: Struct confusion... what am I missing?

2018-03-12 Thread jake6502
Ok, so I looked at the 
https://github.com/tidwall/gjson/blob/master/gjson.go code, and see that 
the jsonvals slice is a slice of:

type Result struct { 
// Type is the json type 
Type Type 
// Raw is the raw json 
Raw string 
// Str is the json string 
Str string 
// Num is the json number 
Num float64 
// Index of raw value in original json, zero means index unknown 
Index int 
}

So you will need to locate the index of the "ID" field in the slice and 
presumably access the Num field. something like:

fmt.Printf("\n%+v\n", jsonvals[2].Num)

Good Luck,
   - Jake


On Monday, March 12, 2018 at 12:32:34 PM UTC-4, Jake Montgomery wrote:
>
> I have not run this. But based on your comments, jsonvals is a slice. So 
> you would presumably need to check the length then access a specific item 
> in the slice like this: fmt.Printf("\n%+v\n", jsonvals[0].ID)
>
> Hope that helps.
>
>
>
> On Monday, March 12, 2018 at 12:01:33 PM UTC-4, asyncp...@gmail.com wrote:
>>
>> Go Noob here, confused about struct. My result is type []gjson.Result but 
>> I can't extract a named value from this struct. Help greatly appreciated, I 
>> have tried several articles.
>>
>> package main
>>
>> import (
>>"fmt"
>>"github.com/tidwall/gjson"
>>"reflect"
>> )
>>
>>
>> func main() {
>>// JSON package gjson
>>const json = `{"pass":true,"balance":180,"who":"f","ID":4231}]`
>>
>>jsonvals := gjson.GetMany(string(json), "pass", "balance", "ID")
>>fmt.Printf("%+v\n", jsonvals)  // result: [true 180 4231]
>>fmt.Println(reflect.TypeOf(jsonvals)) // result: []gjson.Result
>>fmt.Printf("\n%+v\n", jsonvals.ID) // fails here, why? it is a struct, 
>> right???
>>
>> }
>>
>>

-- 
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: Struct confusion... what am I missing?

2018-03-12 Thread jake6502
I have not run this. But based on your comments, jsonvals is a slice. So 
you would presumably need to check the length then access a specific item 
in the slice like this: fmt.Printf("\n%+v\n", jsonvals[0].ID)

Hope that helps.



On Monday, March 12, 2018 at 12:01:33 PM UTC-4, asyncp...@gmail.com wrote:
>
> Go Noob here, confused about struct. My result is type []gjson.Result but 
> I can't extract a named value from this struct. Help greatly appreciated, I 
> have tried several articles.
>
> package main
>
> import (
>"fmt"
>"github.com/tidwall/gjson"
>"reflect"
> )
>
>
> func main() {
>// JSON package gjson
>const json = `{"pass":true,"balance":180,"who":"f","ID":4231}]`
>
>jsonvals := gjson.GetMany(string(json), "pass", "balance", "ID")
>fmt.Printf("%+v\n", jsonvals)  // result: [true 180 4231]
>fmt.Println(reflect.TypeOf(jsonvals)) // result: []gjson.Result
>fmt.Printf("\n%+v\n", jsonvals.ID) // fails here, why? it is a struct, 
> right???
>
> }
>
>

-- 
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: What major API change really is?

2018-03-10 Thread jake6502
This is one of those topics on which everyone has and opinion and no two 
people will agree 100%. I will say that "Go by your gut" is probably bad 
general advice. It works well for folks that have a lot of experience, and 
have done significant reading and research on the topic. But "going with 
your gut" in general is exactly how we have ended up where we are, with so 
many example of bad versioning.  

The go compatibility guarantee is definitely worth a look: 
https://golang.org/doc/go1compat. I also found that this talk by Rich Hickey 
 was a good conceptual 
explanation of breaking changes, and definitely worth watching. (This video 
was linked in https://research.swtch.com/vgo-import by Russ Cox, and is not 
directly about Go.)

Having packages that maintain good backward compatibility seem more common 
in Go than many other languages. They are critical to a thriving Go 
ecosystem. So let's all do the extra work.

On Friday, March 9, 2018 at 8:56:16 AM UTC-5, Maxim Ivanov wrote:
>
> In  the light of recent vgo discussion, I was thinking about what would be 
> major change or and what wouldn't. 
>
> Wanted to ask  Goers, in the new better post vgo world, if you changed 
> exported function argument from *int* to *float*, would you  release your 
> package as v2?
>

-- 
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: Experience report on coming to Go from a C perspective

2018-02-22 Thread jake6502
Have you considered using the new type alias feature introduced in 1.9? 
Line so:

https://play.golang.org/p/6HK8qcuh9UU

This would allow you to change the type of the map in a singe place (the 
type alias) and all the *{}* or *make *would adapt appropriately. 
Disclaimer: I am not espousing this style, just pointing out that it is 
possible.


On Thursday, February 22, 2018 at 3:03:13 PM UTC-5, Devon H. O'Dell wrote:
>
> Hi all, 
>
> It's been some time since I really contributed much of anything to the 
> project (sorry!), but after 8 years, I'm finally writing Go outside of 
> the project itself (and outside of porting efforts). I was lamenting 
> to some coworkers about the lack of a comparable feature to C's 
> "malloc idiom" and they suggested I write an experience report on it. 
> I wrote the bulk of the article a month ago, but finally put in some 
> finishing touches and published. 
>
> For whatever it's worth (probably not much): 
> https://9vx.org/post/a-malloc-idiom-in-go/ 
>
> --dho 
>

-- 
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: printing a struct fields that implements an error interface

2018-02-18 Thread jake6502
There may be another way, but this is one way to print the struct fields:
https://play.golang.org/p/sGZMBGG7r79
See line 17. 

On Sunday, February 18, 2018 at 8:57:02 AM UTC-5, Diego Medina wrote:
>
> using %#v
>
> as in
>
> https://play.golang.org/p/VVqUVsfzx6e
>
>
>
> log.Printf("Hello, playground %#v\n", ret)
>
>
>
> On Saturday, February 17, 2018 at 7:05:42 PM UTC-5, Joseph Lorenzini wrote:
>>
>> Hi all:
>>
>> Per documentation:
>>
>> "If an operand implements the error interface, the Error method will be 
>> invoked to convert the object to a string, which will then be formatted as 
>> required by the verb (if any)"
>>
>> And this is so even if the struct implements the stringer interface. So 
>> if I print the struct, I get the error value. Is there anyway to force 
>> fmt.Print to output the struct fields, even when it implements the error 
>> interface? 
>>
>> Thanks,
>> Joe 
>>
>

-- 
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: making common declarations for several packages?

2018-02-03 Thread jake6502
Referencing a type from another package must specify what package it comes 
from. Try:


var a *common.Any


Also, I would avoid using the term "alias" here. Type aliasing in go is 
totally different from defining a new type, which is what you do here. Type 
aliasing takes the form:

type T1 = T2

Type aliasing was only recently introduced to the language, and intended 
for very specific cases. So I would avoid using it without fully 
understanding the ramifications. 

- Jake


On Saturday, February 3, 2018 at 11:45:22 AM UTC-5, l vic wrote:
>
> I am trying to alias empty interface in one package so it could be used in 
> several other packages:
> in "myproject/common/common.go"
>
> package common
>
> type Any interface{}
>
>
> But when i try to use it from another package "myproject/myutil/myutil.go"
>
> *package myutil*
>
> *import (*
>
> *"*myproject/common"
>
> )
>
> var a *Any
>
>
> I have compilation error:
>
> imported and not used: "myproject/common" 
>
> undefined: Any
>
>
> I declared type Any with capital 'A', so it's supposed to be visible from 
> other packages... Where's the error?
>
>

-- 
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: glog + vendor = "flag redefined: log_dir"?

2018-01-30 Thread jake6502
Ok, maybe I'm a bit off topic. But this also points out why I firmly 
believe that libraries should not add things to the default flag set in an 
init function. This is just one of many cases where that can cause 
problems. 

@Library developers - please, please consider supplying the user with an 
function they can *optionally *call *if* they want to use your flags. 

My 2¢.

Jake

On Tuesday, January 30, 2018 at 8:51:58 AM UTC-5, Marcin Owsiany wrote:
>
> I admit I'm somewhat new to Golang, how do I solve this problem?
> My program uses two libraries, both of which have github.com/golang/glog 
> in their /vendor/ directories.
> This results in a panic at runtime, apparently because two copies of glog 
> try to initialize the same flag on initialization.
>
> Marcin
>

-- 
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: Async process state snapshotting in Golang

2018-01-27 Thread jake6502
A couple of comments. 

This is probably obvious, but I wanted to point out that matthe...'s code 
would require *all *access to the map to be synchronized using the mutex. 
It's a simple and effective solution. One downside to his code is that it 
holds the lock for the duration of the Copy(). This may be unacceptable 
depending on the size of the map and your latency requirements. If the map 
is very, very large, this could block a writer for an indeterminate amount 
of time. 

If your map met the requirements for sync.Map 
, that struct contains a Range() method 
that allows for concurrent access. Depending on the requirements for the 
temporal strictness of the "snapshot", you could then use that function to 
create a copy without blocking other goroutines which might be attempting 
to write to the map. 

There are other, more complicated way that the Copy() lock time could be 
made constant, but they are significantly complicated. 



On Friday, January 26, 2018 at 9:56:38 PM UTC-5, matthe...@gmail.com wrote:
>
> Why not this?
>
> type StructMap map[string]*SomeStruct
>
> type SyncStructMap struct {
> *sync.Mutex // maybe change to *sync.RWMutex if there are mixed 
> read/write synced operations
> StructMap
> }
>
> func (a SyncStructMap) Copy() StructMap {
> out := make(StructMap)
> a.Lock()
> for key, value := range a.StructMap {
> out[key] = value
> }
> a.Unlock()
> return out
> }
>
> // call with go keyword to make it execute concurrently
> func (a SyncStructMap) EncodeAndWrite() {
> c := a.Copy()
> // encode c then write to file
> }
>
> Matt
>
> On Friday, January 26, 2018 at 4:02:09 PM UTC-6, Tamás Gulácsi wrote:
>>
>> Do those *SomeStruct change during map serialization, or only the map 
>> (new keys / delete keys)?
>> If they do, you'll have to lock them too, not just the map access!
>>
>>

-- 
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: "Try Go" in golang.org stopped working properly?

2018-01-27 Thread jake6502
I see the same thing. Changing even one character fixes the problem. Even 
just adding white space to the code. If I copy the example from 
https://golang.org/ to the playground exactly ( 
https://play.golang.org/p/-MKUWeDBml7 ) it also prints nothing. 

Strange

On Saturday, January 27, 2018 at 5:42:44 AM UTC-5, Eyal Posener wrote:
>
> When I "Run", can't see the proper output, just "Program exited".
>
> Only after changing "Hello World" to another example and then back to 
> "Hello World" I see the right output:
>
> Hello, 世界 Program exited.
>

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


Re: [go-nuts] Using reflect to call functions on struct members

2018-01-19 Thread jake6502
I think this 40 second snippet of a talk by Rob Pike 
 is 
apropos. It is not specific to your case, but speaks of reflection in 
general.

On Thursday, January 18, 2018 at 5:20:26 PM UTC-5, Boone Severson wrote:
>
> Ok, asked and answered. Figuring out .Addr() was a key, as was finding the 
> magic incantation to get a handle to a method. I'm curious if there's a 
> better method.
>
> https://play.golang.org/p/49Yj9G0egRI
>
> package main
>
> import (
> "fmt"
> "reflect"
> )
>
> type FooTypeA uint8
> type FooTypeB uint8
>
> type MyStruct struct {
> Foo FooTypeA
> Bar FooTypeB
> }
>
> func (mt *FooTypeA) Validate() bool {
> return *mt > 1
> }
> func (mt *FooTypeB) Validate() bool {
> return *mt > 0
> }
>
> func (ms *MyStruct) Validate() bool {
> s := reflect.ValueOf(ms).Elem()
>
> // Call Validate on all fields
> for i := 0; i < s.NumField(); i++ {
>
> f := s.Field(i).Addr()
> method, _ := f.Type().MethodByName("Validate")
> outs := method.Func.Call([]reflect.Value{f})
> if !outs[0].Bool() {
> return false
> }
> }
> return true
> }
>
> func main() {
>
> mytype := {
> Foo: FooTypeA(2),
> Bar: FooTypeB(5),
> }
>
> fmt.Println("what is mytype? ", mytype)
>
> if !mytype.Validate() {
> fmt.Println("Validation failed")
> }
> }
>

-- 
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: question about golang concurrency

2018-01-08 Thread jake6502
Your use of the sync.Mutex seems sound. At first glance, I see no 
concurrency problems. 

I would suggest running the program with the -race flag. If you make 
memoryCache a package, then perhaps a concurrent test that can be run with 
-race would also be good. In that case you may also want to consider 
renaming `Data` to `data` to prevent others from directly accessing it 
without mutex. 

- Jake

On Monday, January 8, 2018 at 12:38:35 PM UTC-5, Yigit Oztemel wrote:
>
> I have a small question about golang concurrency. I'm using go for an API 
> project and in background, goroutines create/update caches and web requests 
> always get cached data. We are using redis for cache and I want to store a 
> copy of the cache in go variables so we can decrease local network traffic. 
> Because of that I created the following example:
>
> https://github.com/ygto/go-memory-cache/blob/master/main.go
>
> func main() {
>
> c := NewCache()
> wg := sync.WaitGroup{}
> wg.Add(100)
> for i := 0; i < 100; i++ {
> go func(i int) {
> key := fmt.Sprintf("name_%d", i)
> val := fmt.Sprintf("%d", i)
> *c.Set(key, val)*
> *wg.Done()*
> }(i)
> }
> wg.Wait()
> wg = sync.WaitGroup{}
>
> wg.Add(100)
> for i := 0; i < 100; i++ {
> go func(i int) {
> key := fmt.Sprintf("name_%d", i)
> if data, ok := c.Get(key); ok {
> fmt.Println(data)
> }
> wg.Done()
> }(i)
> }
> wg.Wait()
> }
> I highlighted the lines. In my real case, I'm using a framework and it 
> doesn't allow me to send variables c and wg as parameters to func
>
> My question is, Is the above code memory safe? Can it give "concurrent 
> map" error?
>
> Maybe it's not good but is it a pragmatic solution?
>
> 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.


Re: [go-nuts] How to get nice html from godoc?

2017-12-17 Thread jake6502
Thanks Justin I will give it a try. 

(It certainly would be nice if "*godoc -html"* could be useful without 
having to modify the html.)


On Saturday, December 16, 2017 at 6:41:07 PM UTC-5, Justin Israel wrote:
>
>
>
> On Sun, Dec 17, 2017 at 5:47 AM  wrote:
>
>> I suspected it was something like that. I can muddle through, but HTML, 
>> and all that is not really my wheelhouse. Can you give me any more details? 
>>
>>
>>- Where can I find the correct "bundled css/js" files? 
>>
>> https://godoc.org/-/bootstrap.min.css
> https://godoc.org/-/site.css
>  
>
>>
>>- Where do I put them relative to the HTML file?
>>
>> That will be up to you, since you will need to actually format a 
> full-formed html file 
>
>>
>>-  Do I need to modify the HTML file to use them?
>>
>> Yea. The output from godoc -html is only a snippet. You would need to 
> inspect the source of godoc.org to see an example of what you would need 
> to do:
> view-source:https://godoc.org/os
>
> The css files are responsible for formatting the look of the page.
>  
>
>> Thanks
>>
>>   - Jake
>>
>> On Friday, December 15, 2017 at 5:23:59 PM UTC-5, Justin Israel wrote:
>>>
>>>
>>>
>>> On Fri, Dec 15, 2017, 7:35 AM  wrote:
>>>
 I run godoc like this:

  *godoc -html jake\tmp > doc.html* 

 When I open the resulting file (in Chrome or Firefox) the result look 
 terrible. The resulting file is attached. The collapsible sections display 
 as two separate items, are not collapsible, and in Firefox there are 
 strange characters instead of arrows. The preformed text blocks are hard 
 to 
 see, since they contain no special boarder or background and are not 
 indented. The links display all the time as "¶". Etc, etc. 

 So, how can I easily create and view documentation for my library that 
 looks more like the documentation at https://golang.org/pkg/ ?

 Thanks.

>>>
>>> It's because you are missing the css/js files that godoc pages use. In 
>>> my studio build system, for the godoc support in our Go plugin, I have it 
>>> deploying docs with the bundled css/js 
>>>
>> -- 
 You received this message because you are subscribed to the Google 
 Groups "golang-nuts" group.

>>> To unsubscribe from this group and stop receiving emails from it, send 
 an email to golang-nuts...@googlegroups.com.
>>>
>>>
 For more options, visit https://groups.google.com/d/optout.

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

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


Re: [go-nuts] How to get nice html from godoc?

2017-12-16 Thread jake6502
I suspected it was something like that. I can muddle through, but HTML, and 
all that is not really my wheelhouse. Can you give me any more details? 


   - Where can I find the correct "bundled css/js" files? 
   - Where do I put them relative to the HTML file?
   -  Do I need to modify the HTML file to use them?

Thanks

  - Jake

On Friday, December 15, 2017 at 5:23:59 PM UTC-5, Justin Israel wrote:
>
>
>
> On Fri, Dec 15, 2017, 7:35 AM  wrote:
>
>> I run godoc like this:
>>
>>  *godoc -html jake\tmp > doc.html* 
>>
>> When I open the resulting file (in Chrome or Firefox) the result look 
>> terrible. The resulting file is attached. The collapsible sections display 
>> as two separate items, are not collapsible, and in Firefox there are 
>> strange characters instead of arrows. The preformed text blocks are hard to 
>> see, since they contain no special boarder or background and are not 
>> indented. The links display all the time as "¶". Etc, etc. 
>>
>> So, how can I easily create and view documentation for my library that 
>> looks more like the documentation at https://golang.org/pkg/ ?
>>
>> Thanks.
>>
>
> It's because you are missing the css/js files that godoc pages use. In my 
> studio build system, for the godoc support in our Go plugin, I have it 
> deploying docs with the bundled css/js 
>
>> -- 
>> 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: Use golang to call the win API

2017-12-15 Thread jake6502
I have not called a Windows API from go before, so there may be other 
problems with your code. But looking at WlanEnumInterfaces documentation 

 
the last parameter is *not *a pointer to a pointer to a 
WLAN_INTERFACE_INFO_LIST, it is a pointer to a PWLAN_INTERFACE_INFO_LIST. 
So, in C terms. it is a *WLAN_INTERFACE_INFO_LIST***. In other words, you 
should be passing it a *pointer *to a uintptr, then dereferencing it twice 
to get the actual list. 

(Also, don't forget to call *WlanFreeMemory* when you are done.)

Good Luck
 - Jake

On Thursday, December 14, 2017 at 11:15:52 PM UTC-5, 流沙 wrote:
>
> API Address:https://msdn.microsoft.com/en-us/library/ms706716(VS.85).aspx
>
> Code:
>
> package main
>
> // #define WIN32_LEAN_AND_MEAN
> // #include 
>
> import (
>"fmt"
>"syscall"
>"unsafe"
>"C"
> )
> var (
>wlankernal,_ = syscall.LoadLibrary("Wlanapi.dll")
>wlanhandle,_ = syscall.GetProcAddress(wlankernal,"WlanOpenHandle")
>wlanclosehandle,_ = syscall.GetProcAddress(wlankernal,"WlanCloseHandle")
>wlanenumInterfaces,_ = 
> syscall.GetProcAddress(wlankernal,"WlanEnumInterfaces")
>wlangetprofile,_ = syscall.GetProcAddress(wlankernal,"WlanGetProfileList")
> )
> type ulong int32
>
> type WLAN_INTERFACE_INFO  struct{
>InterfaceGuid syscall.GUID
>strInterfaceDescription string
>isState uint
> }
>
> type WLAN_INTERFACE_INFO_LIST struct {
>NumberOfItems uint32
>Index uint32
>InterfaceInfo WLAN_INTERFACE_INFO
> }
>
> type WLAN_PROFILE_INFO struct{
>ProfileName C.char
>Flags ulong
> }
>
> type WLAN_PROFILE_INFO_LIST struct{
>NumberOfItems ulong
>Index ulong
>ProfileInfo WLAN_PROFILE_INFO
> }
>
> func abort(funcname string, err error) {
>panic(fmt.Sprintf("%s failed: %v", funcname, err))
> }
>
> //打开一个WLAN句柄
> func WlanOpenHandle() (result uint32)  {
>negotiated_version := uint32(0)
>client_handle := uint32(0)
>dwClientVersion := uint32(2)
>var nargs uintptr = 4
>ret,_,callErr := syscall.Syscall6(uintptr(wlanhandle),
>   nargs,
>   uintptr(dwClientVersion),
>   0,
>   uintptr(unsafe.Pointer(_version)),
>   uintptr(unsafe.Pointer(_handle)),
>   0,
>   0,
>)
>if ret != 0{
>   abort("StartWLANHandleError", callErr)
>   return
>}
>result = uint32(client_handle)
>return
> }
>
> //关闭WLAN句柄
> func WlanCloseHandle()  {
>var nargs uintptr = 2
>handle :=WlanOpenHandle()
>ret,_,callErr := syscall.Syscall(uintptr(wlanclosehandle),
>   nargs,
>   uintptr(handle),
>   0,
>   0,
>)
>if ret !=0{
>   abort("CloseHandleError",callErr)
>   return
>}
>fmt.Println("WlanCloseHandle Successful")
> }
>
>
> func main()  {
>defer syscall.FreeLibrary(wlankernal)
>var nargs uintptr = 3
>handle :=WlanOpenHandle();
>var wlan_interface_info WLAN_INTERFACE_INFO_LIST;
>ret,_,callErr := syscall.Syscall(uintptr(wlanenumInterfaces),
>   nargs,
>   uintptr(handle),
>   0,
>   uintptr(unsafe.Pointer(_interface_info)),
>)
>if ret !=0{
>   abort("WlanEnumInterfacesError",callErr)
>   return
>}
>WlanCloseHandle()
>fmt.Println(ret)
>fmt.Println(wlan_interface_info)
> }
>
>
>
> wlan_interface_info returns a value of {7306176 0 {{0 0 0 [0 0 0 0 0 0 0 
> 0]}  0}}
> This value seems to be wrong!
> May I ask how to solve this problem?
>
>

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


[go-nuts] Re: go test/flag.NewFlagSet bug?

2017-12-13 Thread jake6502
I'm not sure how you expect the *nfs=true* case to work. The "-data=x" flag 
will be passed to test binary, as described in the documentation.  But the 
test binary is not just your test code, it also contains the testing 
framework, which must run some variant of *flag.Parse()* in order to parse 
its own flags. That is where the error comes in, because the default parser 
does not contain your flag. 

If you add "*flag.StringVar(, "data", datainit, "data")*" to the nfs 
case, then it runs, though I suspect that defeats the purpose. 

Good Luck,
 Jake

On Tuesday, December 12, 2017 at 7:25:37 PM UTC-5, gocss wrote:
>
> when I run the minimal program below it errors about NOT knowing  -data 
> flag:
> go test -v -args -data=x
> flag provided but not defined: -data
> Usage of /tmp/go-build454762170/
> github.com/phcurtis/flagexp/_test/flagexp.test:
>   -test.bench regexp  blah blah,
>
> if you change nfs=false ... and then it uses flag.Parse etc ... code runs 
> without issue
> but I want to handle error cases in other code I'm working and use  the 
> flag.NewFlagSet with go test ...
> note the below code in either case works with go run but not with go test.
>
>
> package main
>
> import (
> "flag"
> "fmt"
> "os"
> "testing"
> )
>
> var data string
> var test func(t *testing.T)
> var datainit = "defValue"
> var nfs = true
>
> func init() {
> if nfs {
> flag3 := flag.NewFlagSet("nfs", flag.ContinueOnError)
> flag3.StringVar(, "data", datainit, "data")
> test = func(t *testing.T) {
> fmt.Println("TP1")
> err := flag3.Parse(os.Args)
> fmt.Printf("data:%v err:%v\n", data, err)
> }
> return
> }
> flag.StringVar(, "data", datainit, "data")
> test = func(t *testing.T) {
> fmt.Println("TP2")
> flag.Parse()
> fmt.Printf("data:%v\n", data)
> }
> }
>
> func Test_code(t *testing.T) {
> test(t)
> }
>
> ***
> heres full output when nfs=true
> paul@t560:~/go/src/github.com/phcurtis/flagexp$ go test -v -args -data=x
> flag provided but not defined: -data
> Usage of /tmp/go-build454762170/
> github.com/phcurtis/flagexp/_test/flagexp.test:
>   -test.bench regexp
> run only benchmarks matching regexp
>   -test.benchmem
> print memory allocations for benchmarks
>   -test.benchtime d
> run each benchmark for duration d (default 1s)
>   -test.blockprofile file
> write a goroutine blocking profile to file
>   -test.blockprofilerate rate
> set blocking profile rate (see runtime.SetBlockProfileRate) 
> (default 1)
>   -test.count n
> run tests and benchmarks n times (default 1)
>   -test.coverprofile file
> write a coverage profile to file
>   -test.cpu list
> comma-separated list of cpu counts to run each test with
>   -test.cpuprofile file
> write a cpu profile to file
>   -test.list regexp
> list tests, examples, and benchmarch maching regexp then exit
>   -test.memprofile file
> write a memory profile to file
>   -test.memprofilerate rate
> set memory profiling rate (see runtime.MemProfileRate)
>   -test.mutexprofile string
> write a mutex contention profile to the named file after execution
>   -test.mutexprofilefraction int
> if >= 0, calls runtime.SetMutexProfileFraction() (default 1)
>   -test.outputdir dir
> write profiles to dir
>   -test.parallel n
> run at most n tests in parallel (default 4)
>   -test.run regexp
> run only tests and examples matching regexp
>   -test.short
> run smaller test suite to save time
>   -test.timeout d
> panic test binary after duration d (0 means unlimited)
>   -test.trace file
> write an execution trace to file
>   -test.v
> verbose: print additional output
> exit status 2
> FAILgithub.com/phcurtis/flagexp0.001s
>
>

-- 
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] Does uintptr count as a refence?

2017-11-26 Thread jake6502
Thanks. That is clear:


*A uintptr is an integer, not a reference. Converting a Pointer to a 
uintptr creates an integer value with no pointer semantics. Even if a 
uintptr holds the address of some object, the garbage collector will not 
update that uintptr's value if the object moves, nor will that uintptr keep 
the object from being reclaimed. *
This makes using the cgo wrapper I am working with more than a bit awkward, 
but I can work around it now that I know the rules.
 

On Sunday, November 26, 2017 at 2:45:46 PM UTC-5, Axel Wagner wrote:
>
> You can find the specific rules in the godoc of the unsafe package 
> .
>
> On Sun, Nov 26, 2017 at 8:12 PM, Jan Mercl <0xj...@gmail.com 
> > wrote:
>
>> On Sun, Nov 26, 2017 at 6:20 PM  wrote:
>>
>> > The core question is does a uintptr derived from a pointer to an object 
>> count as a reference as far as GC is concerned?
>>
>> Within a single expression yes, otherwise no.
>>
>> -- 
>>
>> -j
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to golang-nuts...@googlegroups.com .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

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


  1   2   >