Re: [go-nuts] Loop unit char entered

2024-03-05 Thread Michael Adamus
Daniel,
I'd like to see source code for this if you're able.

Thanks,
Mike

On Saturday, April 16, 2022 at 6:21:30 AM UTC-4 Daniel Jankins wrote:

> Thank you,
> That is what I did.  It works very well.
> Thank you again
>
> On Fri, Apr 15, 2022 at 8:48 PM Kurtis Rader  wrote:
>
>> On Fri, Apr 15, 2022 at 6:35 AM Daniel Jankins  wrote:
>>
>>> I have a newbie question.  I want to loop until a char is available 
>>> (keypress).
>>> Could someone point me to an example.
>>>
>>
>> I can't point you to an example because that wouldn't be idiomatic Go; 
>> thus such examples are (I hope) hard to find. In Go you shouldn't busy wait 
>> using a function like "kbhit 
>> " . You should create a 
>> channel for communicating the keys that are seen, create a goroutine that 
>> reads from os.Stdin and injects keys into that channel, then use an event 
>> loop in a different goroutine that uses "select 
>> " to read key events from 
>> that channel.
>>
>> -- 
>> Kurtis Rader
>> Caretaker of the exceptional canines Junior and Hank
>>
>
>
> -- 
> DanJ
>

-- 
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/549d92b7-009f-4db6-8677-f59050fbdb18n%40googlegroups.com.


[go-nuts] Re: discrepancy between goal heap size and NextGC

2024-01-30 Thread 'Michael Knyszek' via golang-nuts
838103616 bytes is 799 MiB (Mebibytes, the power-of-two-based prefix), 
which matches GC 13. (Note that the computation for the heap goal just 
divides by 1<<20, or 1 MiB.)

The discrepancy in GC count is probably due to the fact that the GC count 
value reported by the GC trace is *after* the increment in mark 
termination, but it reports the previous cycle's heap goal. This makes 
sense because the GC trace isn't reporting a count of completed GCs, but 
reporting on the Nth GC, which just finished. (This is why the GC trace 
count starts at 1 instead of 0.)

More concretely, you'll observe that 799 MiB heap goal after 12 GCs have 
completed (your read of numgc), but you'll be reading that heap goal 
*during* the 13th GC cycle, which is what the GC trace is reporting on.

On Tuesday, January 30, 2024 at 10:48:26 AM UTC-5 Michael Mitchell wrote:

> Might it have something to do with the comment in mgc.go about how the 
> increment of memstats.numgc differs from the increment of GC cycles for 
> gctrace? memstats.numgc seems to get incremented earlier (after mark 
> termination) whereas gctrace waits until the sweep is done.
>
> // cycles is the number of completed GC cycles, where a GC
> // cycle is sweep termination, mark, mark termination, and
> // sweep. This differs from memstats.numgc, which is
> // incremented at mark termination.
> cycles uint32
>
> On Monday, January 29, 2024 at 7:12:53 AM UTC-5 Michael Mitchell wrote:
>
>> In the twelfth garbage collection of a short program I ran, GC trace 
>> reports the goal heap size as 735 MB (see below for gc11, gc12 and gc13 
>> from GC trace)  I also checked runtime Memstats (see attached image), and 
>> it says the nextGC target after 12 GCs have run is 838103616. 
>>
>> Should goal Heap Size of GC Trace and NextGC of runtime.Memstats not be 
>> the same? 
>>
>>
>> gc 11 @22.009s 0%: 0.004+12+0.034 ms clock, 0.019+0.13/11/0.94+0.13 ms 
>> cpu, 562->562->367 MB, 964 MB goal, 4 P
>>
>> gc 12 @32.925s 0%: 0.003+16+0.024 ms clock, 0.014+0/3.7/13+0.099 ms cpu, 
>> 410->410->399 MB, 735 MB goal, 4 P (forced)
>>
>> gc 13 @32.964s 0%: 0.019+21+0.036 ms clock, 0.079+0/21/0.56+0.14 ms cpu, 
>> 400->400->399 MB, 799 MB goal, 4 P (forced)
>>
>

-- 
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/ecfdfe66-9de8-4936-9248-617e8a6a4d03n%40googlegroups.com.


[go-nuts] Re: array index not starting at 0

2024-01-30 Thread 'Michael Knyszek' via golang-nuts
I see that you're on Windows. The clock granularity on Windows is really 
coarse (15 ms) because AFAIK there are no fast fine-grained OS-level clocks 
available.

There are fine-grained clocks, but they're heavyweight. They're too 
heavyweight for many situations in the runtime, but honestly, they're 
probably not too heavyweight in this particular scenario. Alas, the runtime 
tends to just use the default OS clock it picks (the nanotime function) 
everywhere, since the granularity is very fine on most other popular 
platforms.

I suspect that is the cause of all the zeroes. More specifically, the 
measurement happens entirely within a 15 ms epoch. For this particular 
measurement, the runtime just uses that coarse OS clock. As an easier 
workaround, we could probably estimate durations like this from RDTSC 

 
like we do for other things, like some profiles on Windows. This is not 
great for actually measuring timestamps, but it's probably OK (though far 
from perfect) for durations.

Do you mind filing an issue at https://github.com/golang/go/issues? Thanks.

On Tuesday, January 30, 2024 at 5:24:41 PM UTC-5 Leah Stapleton wrote:

> Is it possible that some PauseNs numbers are so small that they're rounded 
> down to 0?
>
> On Monday, January 29, 2024 at 9:45:32 AM UTC-5 Leah Stapleton wrote:
>
>> go version go1.21.5 windows/amd64
>>
>> There have been 9 garbage collections according to NumGC and also the 
>> PauseEnd array; However, the PauseNs array only shows two pause times, and 
>> they are incorrectly positioned in the array (the first time is logged at 
>> PauseNs[4] rather than PauseNs[0])
>>
>> Can anyone provide some information about this. 
>>
>> Leah
>>
>>
>>
>> ,"PauseTotalNs":1999400,"PauseNs":[0,0,0,0,1000100,999300,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"PauseEnd":[1706534601618276400,1706534601625558600,1706534601643261400,1706534601677238900,1706534601781174700,1706534602022683900,1706534602465533900,1706534603516006900,1706534604837389800,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"NumGC":9,
>>
>

-- 
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/617f8e6b-5bd4-4925-b34e-1413ccfc7ef8n%40googlegroups.com.


[go-nuts] Re: discrepancy between goal heap size and NextGC

2024-01-30 Thread Michael Mitchell
Might it have something to do with the comment in mgc.go about how the 
increment of memstats.numgc differs from the increment of GC cycles for 
gctrace? memstats.numgc seems to get incremented earlier (after mark 
termination) whereas gctrace waits until the sweep is done.

// cycles is the number of completed GC cycles, where a GC
// cycle is sweep termination, mark, mark termination, and
// sweep. This differs from memstats.numgc, which is
// incremented at mark termination.
cycles uint32

On Monday, January 29, 2024 at 7:12:53 AM UTC-5 Michael Mitchell wrote:

> In the twelfth garbage collection of a short program I ran, GC trace 
> reports the goal heap size as 735 MB (see below for gc11, gc12 and gc13 
> from GC trace)  I also checked runtime Memstats (see attached image), and 
> it says the nextGC target after 12 GCs have run is 838103616. 
>
> Should goal Heap Size of GC Trace and NextGC of runtime.Memstats not be 
> the same? 
>
>
> gc 11 @22.009s 0%: 0.004+12+0.034 ms clock, 0.019+0.13/11/0.94+0.13 ms 
> cpu, 562->562->367 MB, 964 MB goal, 4 P
>
> gc 12 @32.925s 0%: 0.003+16+0.024 ms clock, 0.014+0/3.7/13+0.099 ms cpu, 
> 410->410->399 MB, 735 MB goal, 4 P (forced)
>
> gc 13 @32.964s 0%: 0.019+21+0.036 ms clock, 0.079+0/21/0.56+0.14 ms cpu, 
> 400->400->399 MB, 799 MB goal, 4 P (forced)
>

-- 
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/374c3535-f243-43fb-a841-f8717bf85a54n%40googlegroups.com.


Re: [go-nuts] Re: Passing 2d arrays from Go to C using runtime.Pinner

2024-01-29 Thread 'Michael Knyszek' via golang-nuts
Thanks for the reproducer. I think I've puzzled out what's going wrong and
it's pretty subtle.

TL;DR: You can work around this by either calling `calloc` or just
allocating `inRows` as Go memory and pinning that as well. The latter will
be safer and faster overall. It's not totally clear to me at this moment
whether just using `calloc` instead should be sufficient. Read on for more
details.

Writing pointers into C memory from Go may invoke a write barrier. The
current write barrier is a hybrid barrier: it writes down the pointers that
are both being written, and those that are being deleted in the write.

In this particular case, we're writing a Go pointer into C memory *from Go*.
If that C memory isn't zeroed *and* it points to some dead Go memory, we
have a problem. That appears to be what's happening here. If I use calloc
instead of malloc to create inRows, the problem goes away. Also, if I
create inRows in Go and pin it, that also works.

I think this is actually documented in the cgo pointer passing rules (
https://pkg.go.dev/cmd/cgo#hdr-Passing_pointers), but we all missed it:

Note: the current implementation has a bug. While Go code is permitted to
write nil or a C pointer (but not a Go pointer) to C memory, the current
implementation may sometimes cause a runtime error if the contents of the C
memory appear to be a Go pointer. Therefore, avoid passing uninitialized C
memory to Go code if the Go code is going to store pointer values in it.
Zero out the memory in C before passing it to Go.


AFAICT, the rest of the page does not say one way or the other whether Go
code writing a Go pointer into C memory is allowed (note that,
counterintuitively, *C.float is a Go pointer, because it may point to Go
memory).

One question that I have to wonder about is whether it's OK to write a Go
pointer into C memory at all and if we should just restrict that like we
did before. The text above already implies that it is not OK, in which case
the code in this thread is invalid and inRows basically must be allocated
on the Go side. However, I think this may also just be an oversight from
when I was updating the documentation for pinning; I think my original
intent was to say that it's OK for Go code to write pinned Go pointers to C
memory.

Anyway, this needs more thought, since allowing Go code to write Go
pointers to C memory (pinned or not) may end up restricting GC
implementations in a way we don't want to. I filed
https://github.com/golang/go/issues/65349 to track this.

On Mon, Jan 29, 2024 at 11:17 AM peterGo  wrote:

> Michael,
>
> The OP appears to have lost interest in debugging. Here's my minimal,
> reproducible example that produces the same fatal errror:
>
> https://go.dev/play/p/flEmSh1euqR (run locally)
>
> If the runtime.GC() statement is uncommented then the fatal error does not
> occur.
>
> The use of this profligate, inefficient algorithm is for debugging
> purposes only. The use of runtime.Pinner is not required. A single
> implicitly pinned C wrapper function argument pointing to contiguous
> underlying slice data arrays would suffice.
>
> Peter
>
>
> On Friday, January 26, 2024 at 12:05:38 PM UTC-5 Michael Knyszek wrote:
>
>> Ignoring more efficient ways to pass memory to C for a moment,
>> superficially I do think your code using Pinner should work. Do you have a
>> full reproducer? It's hard to tell from just looking at your code if your
>> code is the problem, or its just enough to trigger some other cgo issue
>> elsewhere in your codebase. There's a slim chance this is a bug in the
>> Pinner implementation, but that would be surprising to me. The Pinner
>> trivially keeps all pointers passed to it live by just holding onto their
>> references.
>>
>> Also, have you tried running your code with GODEBUG=cgocheck=1 and/or
>> building your code with GOEXPERIMENT=cgocheck2? That might help identify
>> what the issue is.
>> On Friday, January 26, 2024 at 7:05:45 AM UTC-5 Tamás Gulácsi wrote:
>>
>>> To convert a Go slice to C array is easy with unsafe.Slice.
>>>
>>> The problem is that the multi-dimensional C array is an array of
>>> pointers (*(*float64))
>>> which cannot travel between the C/Go barrier.
>>>
>>> In your example, you flatten your slice, and recreate the pointers in
>>> that one big slice.
>>> You could go on with that example, but from the Go side:
>>>
>>> 1. have a "flat" []float64 wihich is N*M
>>> 2. have the [][]float64 as subslices of that one big flattened
>>> []float64: flat[i*M:i*(M+1)]
>>> 3. send that flat slice to the C side with unsafe.Slice
>>> 4. have the C side implement the same subslicing: create a []*float64
>>> array and have each point to the corredt [i*M].
>&

[go-nuts] discrepancy between goal heap size and NextGC

2024-01-29 Thread Michael Mitchell
In the twelfth garbage collection of a short program I ran, GC trace 
reports the goal heap size as 735 MB (see below for gc11, gc12 and gc13 
from GC trace)  I also checked runtime Memstats (see attached image), and 
it says the nextGC target after 12 GCs have run is 838103616. 

Should goal Heap Size of GC Trace and NextGC of runtime.Memstats not be the 
same? 


gc 11 @22.009s 0%: 0.004+12+0.034 ms clock, 0.019+0.13/11/0.94+0.13 ms cpu, 
562->562->367 MB, 964 MB goal, 4 P

gc 12 @32.925s 0%: 0.003+16+0.024 ms clock, 0.014+0/3.7/13+0.099 ms cpu, 
410->410->399 MB, 735 MB goal, 4 P (forced)

gc 13 @32.964s 0%: 0.019+21+0.036 ms clock, 0.079+0/21/0.56+0.14 ms cpu, 
400->400->399 MB, 799 MB goal, 4 P (forced)

-- 
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/91aa0a78-7271-43b5-8fb0-be2f5064b265n%40googlegroups.com.


[go-nuts] Re: Passing 2d arrays from Go to C using runtime.Pinner

2024-01-26 Thread 'Michael Knyszek' via golang-nuts
Ignoring more efficient ways to pass memory to C for a moment, 
superficially I do think your code using Pinner should work. Do you have a 
full reproducer? It's hard to tell from just looking at your code if your 
code is the problem, or its just enough to trigger some other cgo issue 
elsewhere in your codebase. There's a slim chance this is a bug in the 
Pinner implementation, but that would be surprising to me. The Pinner 
trivially keeps all pointers passed to it live by just holding onto their 
references.

Also, have you tried running your code with GODEBUG=cgocheck=1 and/or 
building your code with GOEXPERIMENT=cgocheck2? That might help identify 
what the issue is.
On Friday, January 26, 2024 at 7:05:45 AM UTC-5 Tamás Gulácsi wrote:

> To convert a Go slice to C array is easy with unsafe.Slice.
>
> The problem is that the multi-dimensional C array is an array of pointers 
> (*(*float64))
> which cannot travel between the C/Go barrier.
>
> In your example, you flatten your slice, and recreate the pointers in that 
> one big slice.
> You could go on with that example, but from the Go side:
>
> 1. have a "flat" []float64 wihich is N*M
> 2. have the [][]float64 as subslices of that one big flattened []float64: 
> flat[i*M:i*(M+1)]
> 3. send that flat slice to the C side with unsafe.Slice
> 4. have the C side implement the same subslicing: create a []*float64 
> array and have each point to the corredt [i*M].
> 5. profit
>
>
> Denis a következőt írta (2024. január 26., péntek, 1:18:59 UTC+1):
>
>> I am trying to pass 2d array from Go to some C function void foo(in 
>> **float, out *double). Since I want to have wrapper for this C function, 
>> I'd like that Go function has definition like func 
>> FooWrapper([][]float32) []float64. The easiest but not efficient 
>> implementation is allocating all memory through C that listed below:
>>
>> func FooWrapper(values [][]float32) []float64 {
>> totalObj := len(values)
>> totalParams := len(values[0])
>> results := make([]float64, totalObj)
>>
>> ptrArrLength := uintptr(totalObj) * cPointerSize
>> paramArrLength := uintptr(totalParams) * cFloatSize
>>
>> ptr := C.malloc(C.size_t(ptrArrLength + 
>> paramArrLength*uintptr(totalObj)))
>> defer C.free(ptr)
>>
>> ptrSlice := unsafe.Slice((**C.float)(ptr), totalObj)
>> for i, obj := range values {
>> paramArrPtr := (*C.float)(unsafe.Add(ptr, 
>> ptrArrLength+uintptr(i)*paramArrLength))
>> ptrSlice[i] = paramArrPtr
>>
>> paramSlice := unsafe.Slice(paramArrPtr, totalParams)
>> for j, param := range obj {
>> paramSlice[j] = (C.float)(param)
>> }
>> }
>>
>> C.foo((**C.float)(ptr), (*C.double)([0]))
>>
>> return results
>> }
>>
>> Is that safe implementation? Can I pass pointer of result data? As far 
>> as I know, this pointer will be pinned because it passed to C function.
>>
>> But I want to allocate less memory just reusing Go memory, I've learned 
>> about runtime.Pinner that make pointer pinned until 
>> runtime.Pinner.Unpin() invocation. I tried to write another 
>> implementation using pinner:
>>
>> func FooWrapper(values [][]float32) []float64 {
>> length := len(values)
>> results := make([]float64, length)
>>
>> pinner := runtime.Pinner{}
>> defer pinner.Unpin()
>>
>> arr := (**C.float)(C.malloc(C.size_t(uintptr(length) * cPointerSize)))
>> defer C.free(unsafe.Pointer(arr))
>> slice := unsafe.Slice(arr, length)
>> for i, v := range values {
>> pinner.Pin([0])
>> slice[i] = (*C.float)([0])
>> }
>>
>> C.foo(arr, (*C.double)([0]))
>>
>> return results
>> }
>>
>> But, unfortunately, this code doesn't work
>>
>> runtime: pointer 0xc016ecbfc0 to unused region of span 
>> span.base()=0xc016eca000 span.limit=0xc016ecbfa0 span.state=1
>> fatal error: found bad pointer in Go heap (incorrect use of unsafe or 
>> cgo?)
>>
>> Do I use runtime.Pinner wrong (as far as I know, I can pin slice data)? 
>> Or there is another error in this code. Are there some implementations for 
>> passing 3d (4d and so on) array to C function except for allocatiing and 
>> copying all data to C 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/a38c8372-6767-402a-aa4e-65a0e60dbc75n%40googlegroups.com.


[go-nuts] pauseEnd times in runtime.Memstats

2024-01-12 Thread Michael Mitchell
In runtime.Memstates, one of the stats given is the timestamps for the last 
256 garbage collections in the PauseEnd array, i.e. when those garbage 
collections took place.

So if you subtract one timestamp from another, you can find out how much 
time took place between garbage collections.

Is there anything else that you do with PauseEnd times?  

-- 
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/54b9e68c-942c-40d4-8373-5e9a8bfc5cbdn%40googlegroups.com.


[go-nuts] Re: garbage collections on Windows and Mac

2024-01-09 Thread 'Michael Knyszek' via golang-nuts


On Tuesday, January 9, 2024 at 10:21:26 PM UTC-5 Michael Mitchell wrote:

Hi,

I have noticed on my macbook pro that HeapInUse is always slightly above 
NextGC when the garbage collection occurs.  

According to mstats.go, the "garbage collector's goal is to keep HeapAlloc 
less than NextGC" and also  according to mstats.go, "HeapInUse minus 
HeapAlloc estimates the amount of memory that has been dedicated to 
particular size classes, but is not currently being used" so it makes 
sense   that HeapInUse rises above NextGC, and also that HeapIdle gets 
smaller as we get closer to NextGC. 

However, on my windows machine, as shown in this attached video, the 
garbage collections are occuring well below the NextGC level.  When the 
number of garabge collections changes from 4 to 5, the number of 
Allocations is well below the nextGC level.
https://youtube.com/shorts/jf6DoEQSnMk?feature=share

 On both the Mac and Windows machine, the nextGC level is the same. 

Question: Why is the garbage collection happening much sooner on the 
Windows than the Mac? 

It may not be. It may be an artifact of how the MemStats values are being 
read or possibly a bug in the stats. What is the output of your program 
when you set GODEBUG=gctrace=1 in your environment? I briefly 
double-checked some runtime tests that exercise the GC on a Windows machine 
and everything looked fine (the GC ended at about the right time 
consistently) with the GODEBUG=gctrace=1 output. (I only checked that 
because it was easier to do, and those numbers are come from values much 
closer to the source-of-truth in the GC.) If you are able to share the 
program that produced the output and also the version of Go that you used, 
that would be helpful.

-- 
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/58198399-7842-48c6-82a2-5bf340530ddcn%40googlegroups.com.


[go-nuts] garbage collections on Windows and Mac

2024-01-09 Thread Michael Mitchell
Hi,

I have noticed on my macbook pro that HeapInUse is always slightly above 
NextGC when the garbage collection occurs.  

According to mstats.go, the "garbage collector's goal is to keep HeapAlloc 
less than NextGC" and also  according to mstats.go, "HeapInUse minus 
HeapAlloc estimates the amount of memory that has been dedicated to 
particular size classes, but is not currently being used" so it makes 
sense   that HeapInUse rises above NextGC, and also that HeapIdle gets 
smaller as we get closer to NextGC. 

However, on my windows machine, as shown in this attached video, the 
garbage collections are occuring well below the NextGC level.  When the 
number of garabge collections changes from 4 to 5, the number of 
Allocations is well below the nextGC level.
https://youtube.com/shorts/jf6DoEQSnMk?feature=share

 On both the Mac and Windows machine, the nextGC level is the same. 

Question: Why is the garbage collection happening much sooner on the 
Windows than the Mac? 




-- 
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/eec4d7e3-8c07-401e-999d-be0331e6e47en%40googlegroups.com.


[go-nuts] Re: Low memory utilization when using soft memory limit with GOGC=off

2023-12-06 Thread 'Michael Knyszek' via golang-nuts


On Tuesday, December 5, 2023 at 1:06:19 AM UTC-5 Zhihui Jiang wrote:

Hi there, 

We are running a large scale recommendation system using Golang and we are 
working on some GC related improvement recently. One of the changes we are 
trying to apply is to use soft memory limit with GOGC=off as suggested 
here: https://github.com/golang/go/issues/48409.

But during our testing, the memory usage never reaches the memory limit we 
set. For example, we have 100GB memory available and we set the memory 
limit to 90GB, but the actual memory usage is very low like <50GB. We also 
observed the GC is actually very frequent which cost a lot of CPU time.

That's odd. Are you positive GOGC=off is set correctly? GOGC=0 is not the 
same, and will in fact trigger the garbage collector constantly.

Can you collect the stderr of your program running with GODEBUG=gctrace=1 
set? That'll help identify what's going on. This behavior isn't what I 
would expect, so if you suspect a bug, please file an issue on GitHub.


We had another tweak to set GOGC to a high value like 200, and the memory 
usage is quite close to the memory limit.


I have two questions here:

   1. Is it expected behavior that the memory usage is much lower than 
   memory limit when GOGC is set to off? From the official doc (
   https://github.com/golang/go/issues/48409), it claims " by setting 
   GOGC=off, the Go runtime will always grow the heap to the full memory 
   limit"?

No, I would expect the runtime's total memory use to always be roughly at 
the soft limit in that case.


   1. How is the GC frequency decided when using soft memory limit + 
   GOGC=off? Is there some internal defalut value for GOGC in this case to 
   decide when to GC?

The frequency isn't decided directly. The heap goal (the total target heap 
size) is determined entirely from the memory limit. Approximately: heap 
goal = memory limit - all other memory the runtime is using. The frequency 
then depends on how big your live heap is and how fast your application 
allocates from the live heap size to the total target heap size.


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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/db43725e-58d0-437b-ac24-4e7051e8a121n%40googlegroups.com.


Re: [go-nuts] Go/Python interop

2023-11-27 Thread 'Michael Knyszek' via golang-nuts
On Thu, Nov 23, 2023 at 11:52 AM Sebastien Binet  wrote:

> On Thu Nov 23, 2023 at 15:23 CET, 'Michael Knyszek' via golang-nuts wrote:
> > Also, I'd like to clarify:
> >
> > - [David]: is it a good idea to use cgo for Go-Python interop?
> > - [Michael]: no. better with pipe or RPC
> >
> > I'm wrong about this. A conversation after the meeting clarified a
> > misunderstanding I had about Go->Python calls specifically. Both
> > Go->Python
> > and Python->Go with cgo may very well be preferable to pipe/RPC in many
> > circumstances. :)
>
> I think that, at least for the ML/AI use cases (where the API is
> python-based), tackling this via the cgo dance will be cumbersome:
>
> to access the data or call the methods/functions, one will need to go
> through the C.PyXYZ calls (even though most of the ML/AI modules are
> implemented in C for performances)
>
> this means a world of C.PyIncref/Decref, C-callbacks, ...
> (having done something along these lines with go-python/gopy (a set of
> tools to automatically expose a Go package as a CPython module), I speak
> from "some" experience)
>
> so, I'd tend to agree with your previous self :)
> what did change your mind ?
>
Sure, I recognize that it's still cumbersome and it may be better to use
some language-agnostic protocol to communicate in some cases. I don't have
very much experience with this specific boundary, so maybe I'm now wrong
again for a different reason. :)

My misunderstanding was regarding a concern about concurrent Go->Python
calls locking up the Python interpreter. I've come to understand that this
generally isn't a problem in practice (or no worse than Python execution
already mostly being serialized).

>
> -s
>
> > On Thursday, November 23, 2023 at 3:40:35 AM UTC-5 Sebastien Binet
> > wrote:
> >
> > > On Thu Nov 23, 2023 at 01:24 CET, Eli Bendersky wrote:
> > > > On Wed, Nov 22, 2023 at 11:31 AM Sebastien Binet
> > > > 
> > > > wrote:
> > > >
> > > > > Hi there,
> > > > >
> > > > > In this week "compiler minutes" [1], one can read:
> > > > >
> > > > > """
> > > > > - Go on future platforms (RAM efficiency. NUMA?)
> > > > > - (maybe) Go-Python interop for AI-powered applications
> > > > > - [David]: is it a good idea to use cgo for Go-Python interop?
> > > > > - [Michael]: no. better with pipe or RPC
> > > > > """
> > > > >
> > > > > Would it be possible to have a bit more informations ?
> > > > > What kind of interop is it ? Exchanging binary data ? On disk ?
> > > > > Establishing a protobuf-based-like standard ?
> > > > > Something else ?
> > > > >
> > > >
> > > > All of it, maybe :-)
> > > > We're just exploring the issue, throwing ideas around. There are many
> > > > potential options, each with its own tradeoffs in terms of
> performance
> > > > vs. effort.
> > >
> > > depending on the timescale, one could also imagine having a Go-based
> > > python VM (e.g. github.com/go-python/gpython) that can run a limited
> set
> > > of python modules (even the C-based ones, like pypy did at some point
> ?).
> > > alternatively, "just" rely on pickle-based, Apache Arrow-based or
> numpy
> > > array-based exchanged data.
> > >
> > > for Arrow and numpy, there are already packages that do offer a fair
> > > amount of interop:
> > >
> > > - https://github.com/apache/arrow/tree/main/go
> > > - https://github.com/sbinet/npyio/ (shameless plug.)
> > >
> > > (we could imagine also adding some buffer protocol implementation à la
> > > PEP-3118)
> > >
> > > for pickle, gpython has support up to protocol=3, and gopickle seems
> to
> > > have support for up to 5:
> > > - https://github.com/nlpodyssey/gopickle
> > > (adding support for array.array to gopickle was relatively
> straightforward)
> > >
> > > -s
> > >
> >
> > --
> > 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/cf461932-52bb-4ac1-9690-053bec7e432an%40googlegroups.com
> .
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAFza%2Bu9-%3DeCaQjEQJ5qj5QijRP7TVhXEqEvrm%2BLuRdqDAx-Ftw%40mail.gmail.com.


Re: [go-nuts] Go/Python interop

2023-11-23 Thread 'Michael Knyszek' via golang-nuts
Also, I'd like to clarify:

- [David]: is it a good idea to use cgo for Go-Python interop?
- [Michael]: no. better with pipe or RPC

I'm wrong about this. A conversation after the meeting clarified a 
misunderstanding I had about Go->Python calls specifically. Both Go->Python 
and Python->Go with cgo may very well be preferable to pipe/RPC in many 
circumstances. :)
On Thursday, November 23, 2023 at 3:40:35 AM UTC-5 Sebastien Binet wrote:

> On Thu Nov 23, 2023 at 01:24 CET, Eli Bendersky wrote:
> > On Wed, Nov 22, 2023 at 11:31 AM Sebastien Binet
> > 
> > wrote:
> >
> > > Hi there,
> > >
> > > In this week "compiler minutes" [1], one can read:
> > >
> > > """
> > > - Go on future platforms (RAM efficiency. NUMA?)
> > > - (maybe) Go-Python interop for AI-powered applications
> > > - [David]: is it a good idea to use cgo for Go-Python interop?
> > > - [Michael]: no. better with pipe or RPC
> > > """
> > >
> > > Would it be possible to have a bit more informations ?
> > > What kind of interop is it ? Exchanging binary data ? On disk ?
> > > Establishing a protobuf-based-like standard ?
> > > Something else ?
> > >
> >
> > All of it, maybe :-)
> > We're just exploring the issue, throwing ideas around. There are many
> > potential options, each with its own tradeoffs in terms of performance
> > vs. effort.
>
> depending on the timescale, one could also imagine having a Go-based 
> python VM (e.g. github.com/go-python/gpython) that can run a limited set 
> of python modules (even the C-based ones, like pypy did at some point ?).
> alternatively, "just" rely on pickle-based, Apache Arrow-based or numpy 
> array-based exchanged data.
>
> for Arrow and numpy, there are already packages that do offer a fair 
> amount of interop:
>
> - https://github.com/apache/arrow/tree/main/go
> - https://github.com/sbinet/npyio/ (shameless plug.)
>
> (we could imagine also adding some buffer protocol implementation à la 
> PEP-3118)
>
> for pickle, gpython has support up to protocol=3, and gopickle seems to 
> have support for up to 5:
> - https://github.com/nlpodyssey/gopickle
> (adding support for array.array to gopickle was relatively straightforward)
>
> -s
>

-- 
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/cf461932-52bb-4ac1-9690-053bec7e432an%40googlegroups.com.


Re: [go-nuts] Shrinking pprof data for PGO through quantization.

2023-11-09 Thread 'Michael Pratt' via golang-nuts
Hi Adam,

Thanks for sending this, lots of interesting ideas here!

I've been meaning for a long time to have more concrete guidelines for how
much data collection is enough for good results, to include on
https://go.dev/doc/pgo.

I also think it would be valuable to provide tooling that can help minimize
file sizes. I played with this a bit last year, with results in
https://go.dev/cl/449500. In this CL I experimented with a few approaches:
truncating stacks (as you mention, though it seems this part didn't make it
into the code in my CL?), as well as aggregation: I drop PCs entirely since
the compiler can't use them anyway, and drop line numbers from leaf
functions since they don't matter to our current optimizations. Another
thing you'll see the source of that tool do is truncate the profile to 99%
CDF. i.e., drop all any samples in the coldest 1% of the application. This
is not a lossless operation because the compiler performs its own CDF
computations to determine which calls are hot and by removing some of the
total sample weight from the profile the compiler will probably decide a
few functions on the edge are no longer hot. To do this losslessly, I think
we'd need to keep the remaining weight in the profile as a single "unknown"
sample and have the compiler always sort that last.

Some other thoughts inline below:

On Thu, Nov 9, 2023 at 3:15 PM 'Adam Azarchs' via golang-nuts <
golang-nuts@googlegroups.com> wrote:

> It's great that we have PGO support in go now, and it's relatively easy to
> use.  One thing that is of mild concern to me is that typically one will be
> checking the default.pgo file in to the repo, and git is notoriously not
> great at handling binary blobs that are updated  frequently.  Its "diff
> compression" doesn't really work on compressed data, of course, which means
> that in a standard (non-shallow) clone that pulls down all history, over
> time it can contribute significantly to time to clone and size of the
> `.git` directory.  git lfs avoids the cumulative burden over time, but has
> its own set of problems.  At a few hundred kB each, they're not so
> concerning, but if you had for example an automated system that collected
> data from production and updated the profile data every few days (which you
> want to do if you're deploying new code that often), possibly for multiple
> executables, it starts to add up.  So far I've been recompressing the pprof
> data (which is automatically gzip-compressed) with zopfli, but I was
> thinking about making a tool to do better than that.
>
> Firstly, we can drop entries from the mappings table if they aren't
> referenced by any locations in samples.  For a linux cgo binary this will
> include stuff like libc.  We can then also drop corresponding entries from
> the string table.
>
> We can drop values for sample_types which are not of interest
> .
> That is, the first sample_type that is "samples"/"count" or
> "cpu"/"nanoseconds".  Most profiles seem to have both, but we only need to
> keep one of them.
>
> Next, it seems like PGO ignores all but the last two stack frames
> .
> This is of course an implementation detail subject to change, but the logic
> for why it does this is sound, and so it's probably still safe to truncate
> stack frames at least somewhat.  Doing so would likely permit many samples
> to be merged, which could significantly reduce the uncompressed size of the
> profile.
>
> A pprof profile is, for purposes of PGO, effectively table of execution
> stacks and how often they were sampled.  If you want to get really good
> profiling data, you do as the PGO guide tells you
>  and collect multiple samples and merge
> them, which gets you more coverage, but also makes for larger, more varied
> sample counts, which decreases the effectiveness of compression.  For
> purposes of PGO, we only care about the relative frequency of different
> code paths at a pretty coarse granularity.  There's two opportunities here.
>
> Normalizing and quantizing the sample counts should be possible to do with
> no significant effect on the accuracy or usefulness to PGO, and would
> improve the effectiveness of compression.  That is, you could for example
> round each sample count to the nearest power of N, and then scale them all
> so that the smallest sample count is N (where N is e.g. 2).  The effect of
> this would likely be minor, since most of the space in the profile is taken
> up by other things like the location and function tables, but it wouldn't
> hurt.
>

This sounds feasible, but, as you say, I imagine the impact on the final
size would be very small.



>
> The other, much more complicated thing we can do is merge sampled
> locations.  PGO is using the profile data to improve its guesses about
> 

[go-nuts] Re: Why golang's garbage collector didn't free obj when an finalizer is associate with it?

2023-11-07 Thread 'Michael Knyszek' via golang-nuts


On Tuesday, November 7, 2023 at 2:32:28 AM UTC-5 Jan wrote:

Btw, I don't follow the sentence:

"the GC necessarily has to keep referents of the object-to-be-finalized 
live even if the object isn't referenced anymore"

That is true for objects not in cycles that need to be finalized as well. 
I'm not sure I follow the reasoning here ...

That fact alone isn't enough. When you couple that fact with the fact that 
cycles can be arbitrarily deep, then you have a problem.

Sorry, this is perhaps a weird framing since it's based on the 
implementation details. Where I'm starting from is the example at the top 
of this post, which is a cycle that has only a single finalizer. The point 
I'm trying to make is that even having just a single finalizer in a cycle 
is a problem. AFAICT, the dependency rules that both the Go GC and the 
Boehm GC state could still be respected if each strongly connected 
component of objects had just a single finalizer, since that entire 
component could be finalized and freed before the next, and the ordering of 
finalizers is preserved. (If I'm wrong about this point, disregard me. I'm 
pretty sure but not certain that one could design a GC that did this.) But 
having to identify such connected components would be a significant 
performance limitation.


Asking about it in Bard <http://bard.google.com>, it explains:

" 
In Go, objects that are in a cyclic structure and that are marked with a 
finalizer (with SetFinalizer) don't get garbage collected when there are no 
more live pointers to the cyclic structure because the garbage collector 
cannot determine a safe order to run the finalizers.
"

Which seems to match the  Boehm collector 
<https://www.hboehm.info/gc/finalization.html> explanation, described 
under "Topologically Ordered Finalization".

That is also true, but AFAICT only really applies to cycles containing more 
than one finalizer. If a cycle (and I think more specifically, a strongly 
connected component of objects) has just one finalizer, one could argue 
such an ordering problem doesn't exist (unless I'm missing something of 
course). Nonetheless, the cycle still isn't collected.


On Tuesday, November 7, 2023 at 3:51:58 AM UTC+1 Michael Knyszek wrote:

Yes, cycles containing a finalizer aren't guaranteed to be freed. As others 
have pointed out, this is documented. SetFinalizer is really designed for a 
narrow set of use-cases, so concessions were made for overall GC 
performance. This case is one of them.

IIUC, the core problem is a combination of the fact that the cycle can be 
arbitrarily deep and the GC necessarily has to keep referents of the 
object-to-be-finalized live even if the object isn't referenced anymore. 
The GC must follow the pointers in an object's referents, and eventually it 
may come upon the almost-dead object it started from. But at that point it 
likely has no knowledge of where it came from. It's just a pointer on a 
queue. A GC could be implemented that keeps track of where the pointers it 
follows came from, but such an implementation would be substantially less 
performant.

Other GCs make the same choice. See the Boehm collector 
<https://www.hboehm.info/gc/finalization.html>, for example.
On Monday, November 6, 2023 at 10:20:39 AM UTC-5 Harish Ganesan wrote:

Does this behaviour mean that, those memory will never be freed and keep 
piling on ? That can be disastrous.

On Monday, November 6, 2023 at 3:39:50 PM UTC+5:30 Jan wrote:

For what it's worth, a bit of "memory management" on structures in many 
cases is very ok (not sure if in your case). So for your cyclic structure 
with finalizers, requiring the user of your code to call some "Finalize()" 
method (some destructor method you define) that manually breaks the cycle, 
often is an ok solution. Fundamentally, it's the same as requiring someone 
to call Close() on an opened file (or any other resource, like sockets, db 
connections, etc).

As an anecdote, previously when I was doing C++ I was a big fan of 
referenced counted smart pointers (`shred_ptr<>`), which gets most of the 
benefit of GC, but with a much lower cost. They required manually breaking 
cycles, which I didn't find to be an issue at all in the great majority of 
the cases.

On Monday, November 6, 2023 at 11:01:04 AM UTC+1 Jan wrote:

I was very surprised by this behavior of SetFinalizer: and indeed if you 
remove the SetFinalizer one can see that s1 is freed, because the memory 
reported by `m.HeapAlloc` goes back down.

I think you already have the answer: the block that has the cycle (s1 and 
s2) have a SetFinalizer set, and it will never run, per documentation (I 
had never paid attention to this).

A suggestion to work around would be to move the stuff that needs a 
"Finalizer" to a leaf node, as in:

https://go.dev/play/p/WMMTdAza6aZ

But I understand this is not a solution if the finalizer needs to access 
the S1 (so, if

[go-nuts] Re: Why golang's garbage collector didn't free obj when an finalizer is associate with it?

2023-11-06 Thread 'Michael Knyszek' via golang-nuts
Yes, cycles containing a finalizer aren't guaranteed to be freed. As others 
have pointed out, this is documented. SetFinalizer is really designed for a 
narrow set of use-cases, so concessions were made for overall GC 
performance. This case is one of them.

IIUC, the core problem is a combination of the fact that the cycle can be 
arbitrarily deep and the GC necessarily has to keep referents of the 
object-to-be-finalized live even if the object isn't referenced anymore. 
The GC must follow the pointers in an object's referents, and eventually it 
may come upon the almost-dead object it started from. But at that point it 
likely has no knowledge of where it came from. It's just a pointer on a 
queue. A GC could be implemented that keeps track of where the pointers it 
follows came from, but such an implementation would be substantially less 
performant.

Other GCs make the same choice. See the Boehm collector 
, for example.
On Monday, November 6, 2023 at 10:20:39 AM UTC-5 Harish Ganesan wrote:

> Does this behaviour mean that, those memory will never be freed and keep 
> piling on ? That can be disastrous.
>
> On Monday, November 6, 2023 at 3:39:50 PM UTC+5:30 Jan wrote:
>
>> For what it's worth, a bit of "memory management" on structures in many 
>> cases is very ok (not sure if in your case). So for your cyclic structure 
>> with finalizers, requiring the user of your code to call some "Finalize()" 
>> method (some destructor method you define) that manually breaks the cycle, 
>> often is an ok solution. Fundamentally, it's the same as requiring someone 
>> to call Close() on an opened file (or any other resource, like sockets, db 
>> connections, etc).
>>
>> As an anecdote, previously when I was doing C++ I was a big fan of 
>> referenced counted smart pointers (`shred_ptr<>`), which gets most of the 
>> benefit of GC, but with a much lower cost. They required manually breaking 
>> cycles, which I didn't find to be an issue at all in the great majority of 
>> the cases.
>>
>> On Monday, November 6, 2023 at 11:01:04 AM UTC+1 Jan wrote:
>>
>>> I was very surprised by this behavior of SetFinalizer: and indeed if you 
>>> remove the SetFinalizer one can see that s1 is freed, because the memory 
>>> reported by `m.HeapAlloc` goes back down.
>>>
>>> I think you already have the answer: the block that has the cycle (s1 
>>> and s2) have a SetFinalizer set, and it will never run, per documentation 
>>> (I had never paid attention to this).
>>>
>>> A suggestion to work around would be to move the stuff that needs a 
>>> "Finalizer" to a leaf node, as in:
>>>
>>> https://go.dev/play/p/WMMTdAza6aZ
>>>
>>> But I understand this is not a solution if the finalizer needs to access 
>>> the S1 (so, if the finalizer function needs any information that is not 
>>> self-contained in `S1Data` in my example).
>>> On Sunday, November 5, 2023 at 4:01:14 PM UTC+1 Soren Yang wrote:
>>>
 As shown in the following code:

 cyclic structure with finalizer 

 The s1 & s2 didn't been free, and finalizer didn't run. But when enable 
 the line which have been commented, all run as expected(s1 & s2 been free)。

 I have seen the comment in runtime.SetFinalizer: If a cyclic structure 
 includes a block with a finalizer, that cycle is not guaranteed to be 
 garbage collected and the finalizer is not guaranteed to run, because 
 there 
 is no ordering that respects the dependencies.

 But why it haven't been free in first code?

>>>

-- 
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/e61586f2-386c-4a3b-ad9b-42dfe9754946n%40googlegroups.com.


Re: [go-nuts] Suggestions on optimizing Go GC

2023-10-30 Thread 'Michael Knyszek' via golang-nuts
I second Jason's message, and +1 to off-heap memory as a last resort. Here 
are a few more details:

For a starting point on how to reduce memory allocations directly, see 
https://go.dev/doc/gc-guide#Optimization_guide. Note that this may require 
restructuring your program in places. (e.g. passing byte slices to 
functions to be filled instead of returning byte slices; that sort of 
thing.)
RE: pooling memory, take a look look at sync.Pool (
https://pkg.go.dev/sync#Pool). A sync.Pool can be really effective at 
reducing the number of memory allocations that are made in the steady-state.

On Monday, October 30, 2023 at 2:33:21 PM UTC-4 Jason E. Aten wrote:

> Similar to Robert's suggestion, you could just use non-GC-ed memory within 
> the process.
>
> https://github.com/glycerine/offheap provides an example. 
>
> The central idea is that the Go GC will never touch memory that you have 
> requested
> yourself from the OS. So you can make your own Arenas. 
> https://en.wikipedia.org/wiki/Region-based_memory_management
>
> But I would save these as last resorts of course. Before that:
>
> a) can you reduce the objects allocated per request?  
> b) can you allocate everything else on the stack? There are flags to see 
> why things are escaping to the heap, use those in your analysis.
> (This is by far the simplest and fastest thing. Since the stack is 
> automatically unwound when the user request finishes, typically, there is 
> no GC to do.)
> c) can you allocate a pool of objects that is just reused instead of 
> allocating for each new user request?
> d) Is there anything that can be effectively cached and re-used instead of 
> allocated?
>
> Use the profiler pprof to figure out what is going on.
>

-- 
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/184e160a-d30d-43e4-a822-b7dc61a03b1bn%40googlegroups.com.


Re: [go-nuts] Question about runtime.Pinner

2023-10-12 Thread 'Michael Knyszek' via golang-nuts


On Thursday, October 12, 2023 at 9:55:12 AM UTC-4 Ian Lance Taylor wrote:

On Thu, Oct 12, 2023 at 5:06 AM Pascal Costanza 
 wrote: 
> 
> I have a question about runtime.Pinner: The documentation states that you 
can only pin an object when it’s the result of calling new, taking the 
address of a composite literal, or taking the address of a local variable. 
> 
> At the same time, the Go language specification states that a slice 
created with make allocates a hidden array, and gives the example that 
make([]int, 50, 100) is the same as new([100]int)[0:50]. 
> 
> Taken together, this suggests that the following sequence should be 
correct: 
> 
> var p runtime.Pinner 
> s := make([]int, 100) 
> p.Pin([0]) 
> 
> …since [0] can be understood as being the result of calling new. 
> 
> Is that intended? 

Yes.

I always figured it at least wasn't unintended and that's why this hasn't 
been some bug to be fixed. But it is also true that you can't just pass a 
slice or string directly to Pin, and IMO it's a bit strange as to why 
that's not allowed when [0] works. Perhaps I'm missing something.




> Also: I believe it would be good if the documentation would state that 
the zero value for type runtime.Pinner is ready to use. 

That's the general default behavior for types in the standard library. 
If nothing says otherwise, the zero value is ready to use. That said, 
I'm not opposed to mentioning it if someone wants to send a patch. 

Ian 

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/d6157537-5e61-41f6-a5bc-6853c97ee67dn%40googlegroups.com.


[go-nuts] Re: Question about runtime.Pinner

2023-10-12 Thread 'Michael Knyszek' via golang-nuts

On Thursday, October 12, 2023 at 8:07:02 AM UTC-4 Pascal Costanza wrote:

Hi, 

I have a question about runtime.Pinner: The documentation states that you 
can only pin an object when it’s the result of calling new, taking the 
address of a composite literal, or taking the address of a local variable.



At the same time, the Go language specification states that a slice created 
with make allocates a hidden array, and gives the example that make([]int, 
50, 100) is the same as new([100]int)[0:50].

Taken together, this suggests that the following sequence should be correct:

var p runtime.Pinner
s := make([]int, 100)
p.Pin([0])

…since [0] can be understood as being the result of calling new.

I think that's not quite following the spirit of the documentation, but as 
you point out, it's already possible to pin (and call runtime.SetFinalizer) 
on memory that doesn't strictly follow the documentation. It's even 
possible to pin strings, but it requires unsafe.StringData (or something 
similar).

I'm of the opinion that we should broaden the scope of runtime.Pinner at 
least slightly, to allow for things like slices and strings explicitly. 
Sometime soon I'll file a proposal about this since it's very technically 
an API change. In the same vein, the cgo pointer passing rules have some 
restrictions that I'm not sure are necessary, but I'm concerned that I may 
be missing something subtle and I haven't had the time to think about it 
more thoroughly. (All of this stuff is pretty subtle.)



Is that intended?

Also: I believe it would be good if the documentation would state that the 
zero value for type runtime.Pinner is ready to use.

That is a good point. I'll send a doc change for that. 




Thanks,
Pascal

-- 
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/1b14537e-e4a8-4091-9a23-132c5b599a87n%40googlegroups.com.


[go-nuts] Re: go 1.21 tuned gc: what's it about?

2023-08-07 Thread 'Michael Knyszek' via golang-nuts
I saw this post a while back and forgot to reply; sorry about that. It's 
about this issue  but also a 
little bit about this issue . 
Both of those problems can be summarized as the GC pacing itself for the 
exact optimal point in couple different cases. Both of those problems are 
resolved by fine-tuning how the GC paces itself.

On Monday, June 26, 2023 at 12:17:32 AM UTC-4 cheng dong wrote:

> Hi there, thanks for having me here.
>
> the go 1.21rc2 release note says "there are 40% reduction in tail latency 
> thanks to gc tuning". im very interesting in what's it about and how it 
> improve app latency.
>
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/a856f3fd-a59f-4408-b598-2af28d6e60ben%40googlegroups.com.


[go-nuts] Re: Maybe a Bug? The Go compiler stores a stack pointer into a global object

2023-08-03 Thread 'Michael Knyszek' via golang-nuts
That line (the full sentence is "The garbage collector now includes 
non-heap sources of garbage collector work (e.g., stack scanning) when 
determining how frequently to run.") is unrelated. It only refers to a 
change in accounting for what gets included in the GOGC calculation, not a 
change in what was marked and scanned by the GC.

On Thursday, August 3, 2023 at 1:41:35 AM UTC-4 Qingwei Li wrote:

> I notice that Go1.17.7 still allocates the array on heap by calling 
> newobject while Go1.18 allocates the array on stack. I also notice that in 
> the release note of Go1.18 that "The garbage collector now includes 
> non-heap sources of garbage collector work". Does the GC in 1.18 and 
> following versions of Go ignore some global memory area when marking?
>
> On Thursday, August 3, 2023 at 1:03:31 AM UTC+8 Jinbao Chen wrote:
>
>> I use go1.20.5 to compile the following code. 
>> package main
>>
>> func use(...interface{}) {
>>   
>> }
>>
>> func main() {
>> testCases := [...][][]int{
>> {{42}},
>> {{1, 2}},
>> {{3, 4, 5}},
>> {{}},
>> {{1, 2}, {3, 4, 5}, {}, {7}},
>> }
>> for _, testCase := range testCases {
>> use(testCase)
>> }
>> }
>> In the generated SSA and assembly code, I notice that the Go compiler 
>> generates some instructions that store a stack pointer(point to the 
>> stack-allocated array) into a global slice header.
>>
>> Just like the assembly code below, the MOV instruction at 0x4585bf stores 
>> a stack pointer into a global object: 
>>   0x458589 48c7442408   MOVQ $0x0, 0x8(SP) 
>>   0x458592 48c74424082a00 MOVQ $0x2a, 0x8(SP) 
>> testCases := [...][][]int{
>>   0x45859b 48c705c28e06000100 MOVQ $0x1, 0x68ec2(IP) 
>>   0x4585a6 48c705bf8e06000100 MOVQ $0x1, 0x68ebf(IP) 
>>   0x4585b1 833d988d09 CMPL $0x0, runtime.writeBarrier(SB) 
>>   0x4585b8 750e JNE 0x4585c8 
>>   0x4585ba 488d442408 LEAQ 0x8(SP), AX 
>>   0x4585bf 4889059a8e0600 MOVQ AX, 0x68e9a(IP) 
>>   0x4585c6 eb11 JMP 0x4585d9 
>>   0x4585c8 488d3d918e0600 LEAQ 0x68e91(IP), DI 
>>   0x4585cf 488d442408 LEAQ 0x8(SP), AX 
>>   0x4585d4 e8e7cf CALL runtime.gcWriteBarrier(SB) 
>>
>> I have read the comments in slicelit 
>> ,
>>   
>> but I didn't find any operations that can generate such stores. As far as I 
>> know, pointers to stack objects cannot be stored in global objects. So is 
>> this a compiler bug? Or the Go compiler does this on purpose to achieve 
>> some optimization I don't know yet?
>>
>> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/74ee4bb3-da1b-4db9-a3df-e38d1df28b2dn%40googlegroups.com.


[go-nuts] Re: about "hybrid barrier"

2023-07-30 Thread 'Michael Knyszek' via golang-nuts


On Friday, July 28, 2023 at 8:05:03 AM UTC-4 metronome wrote:

Hi,

I came across two questions regarding the hybrid barrier that I am hoping 
someone can help with.


1.

Chang https://go-review.googlesource.com/c/go/+/31765 says:

*"It's unconditional for now because barriers on channel operations require 
checking both the source and destination stacks and we don't have a way to 
funnel this information into the write barrier at the moment."*

Can anyone help in understanding the statement, say with a sample? Isn't 
"channel operations involving both stacks" already covered by 
runtime.sendDirect?

Here's my best guess: at the time this CL was written, sendDirect called 
typeBitsBulkBarrier which in turn called writebarrier_prewrite and then 
gcmarkwb_m (the generic non-assembly write barrier function). gcmarkwb_m, 
however, didn't have any knowledge of the context around the pointers being 
written and deleted, or the stack it would've been running on. Information 
about both the source and destination stacks would have had to be passed 
down through those other functions. It could be done, but it's a lot of 
context to pass around for just one corner case.

Though, honestly, I believe the true reason the write barrier was made 
unconditional was because the performance was good enough and it's more 
complex to make it conditional.

In fact, I suspect this is why the hybrid write barrier is still 
unconditional to this day. It also looks very different! The write barrier 
no longer directly marks objects and instead it enqueues the relevant 
pointers in the write barrier buffer system, so there's no write barrier 
routine to plumb this information down into. There may be some ways to make 
it conditional (this TODO f 
or
 
instance) but I don't think anyone is planning to work on it. My gut 
feeling is that the complexity and cost of plumbing this information 
through (or acquiring and using it at the point of the write barrier) might 
not be worth whatever modest performance improvement we would get out of 
it. It would still be interesting to try and find out; I'm happy to be 
wrong. :)

2. comments in mbarrier.go says

// The insertion part of the barrier

// is necessary while the calling goroutine's stack is grey. In

// pseudocode, the barrier is:

//

// writePointer(slot, ptr):

// shade(*slot)

// if current stack is grey:

// shade(ptr)

// *slot = ptr

What does "grey stack" mean? Is a stack considered 'grey' right after its 
goroutine gets suspended, scanned and resumed to execution?

Thanks a lot.

A goroutine stack is a GC mark root, so I believe in this terminology it's 
implicitly grey at the start of the mark phase. It then transitions to 
black once it gets scanned.

-- 
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/0ae11cc2-73eb-4467-9abe-5db1aee5b11an%40googlegroups.com.


[go-nuts] Re: Possible Go Compiler or Runtime bug?

2023-07-27 Thread 'Michael Knyszek' via golang-nuts

On Thursday, July 27, 2023 at 6:16:57 PM UTC-4 Michael Knyszek wrote:

I believe this is working as intended, because I don't think the spec 
<https://go.dev/ref/spec#Conversions> makes any guarantees about the 
capacity of the slice you get back from a conversion.

 (Other than the fact that the capacity must always be >= the length.)


On Thursday, July 27, 2023 at 8:57:58 AM UTC-4 Brian Candler wrote:

Interesting:
https://play.golang.com/p/nSZ7tKSeot4

With the Printf commented out, it shows t has a cap of 32.  With Printf 
uncommented, the cap drops to 0.  Maybe the slice buffer is allocated on 
the stack in one case, and the heap on another?

The slice header of 24 bytes shouldn't have anything to do with this. The 
cap() of a slice relates to the amount of storage allocated for the data 
elements (which the header points to), not the space consumed by the header 
itself.

On Thursday, 27 July 2023 at 13:42:21 UTC+1 Brian Candler wrote:

That looks very weird. The panic is triggered if I uncomment line 17 (the 
final fmt.Printf) even though it never reaches there - it panics when 
getStrBytes is called from line 9 (in line 23).

On Thursday, 27 July 2023 at 13:12:40 UTC+1 Kyle Harrity wrote:

I first asked this on https://reddit.com/r/golang but the contribution 
guide on github recommends this forum, so I'll post here before finally 
raising an issue on github if this appears to be a real bug.

ORIGINAL POST:

I came across this issue in some code I was reviewing today where a string 
is converted into a []byte and then a 32 byte slice is taken from that and 
returned. It returns a 32 byte slice even if the string is empty or less 
than 32 bytes in length as long as its not a string literal (comes from a 
function or stored in variable). I can index the slice normally and iterate 
over its elements, but attempting to print it with fmt.Printf causes a 
runtime error where it realizes the capacity is not actually 32. Trying to 
get a slice larger than 32 fails though smaller slices are okay. I think 
that has something to do with the storage needed to describe a slice 8 
bytes for memory location, 8 bytes for size, 8 bytes for capacity, 8 for 
padding as explained here: 
https://stackoverflow.com/questions/67839752/why-does-an-empty-slice-have-24-bytes

Here's a playground demo: https://play.golang.com/p/yiLPvRYq8PJ 

Maybe this is a known issue and or expected behavior so I thought I'd ask 
here before raising an issue on github.

-- 
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/8fdee71a-c30a-443b-894e-a589b43ec33en%40googlegroups.com.


[go-nuts] Re: Possible Go Compiler or Runtime bug?

2023-07-27 Thread 'Michael Knyszek' via golang-nuts
The number 32 for the capacity comes from this constant 
,
 
and the returned byte slice in that case is likely coming from a 
compiler-inserted call to stringtoslicebyte 
.
 
An empty string is correctly replaced by a zero-length byte slice, it just 
so happens that the capacity of the array backing that slice may or may not 
be zero. As Brian said, commenting or uncommenting that line likely just 
leads to the byte slice's backing array being allocated differently.

I believe this is working as intended, because I don't think the spec 
 makes any guarantees about the 
capacity of the slice you get back from a conversion. On the one hand, it 
is a little surprising given that the make builtin very explicitly sets the 
capacity of the slice 
. On the other 
hand, append  is an 
example of a built-in that may return a slice with a larger capacity than 
requested, so it's not like this case is the only outlier.

On Thursday, July 27, 2023 at 8:57:58 AM UTC-4 Brian Candler wrote:

> Interesting:
> https://play.golang.com/p/nSZ7tKSeot4
>
> With the Printf commented out, it shows t has a cap of 32.  With Printf 
> uncommented, the cap drops to 0.  Maybe the slice buffer is allocated on 
> the stack in one case, and the heap on another?
>
> The slice header of 24 bytes shouldn't have anything to do with this. The 
> cap() of a slice relates to the amount of storage allocated for the data 
> elements (which the header points to), not the space consumed by the header 
> itself.
>
> On Thursday, 27 July 2023 at 13:42:21 UTC+1 Brian Candler wrote:
>
>> That looks very weird. The panic is triggered if I uncomment line 17 (the 
>> final fmt.Printf) even though it never reaches there - it panics when 
>> getStrBytes is called from line 9 (in line 23).
>>
>> On Thursday, 27 July 2023 at 13:12:40 UTC+1 Kyle Harrity wrote:
>>
>>> I first asked this on https://reddit.com/r/golang but the contribution 
>>> guide on github recommends this forum, so I'll post here before finally 
>>> raising an issue on github if this appears to be a real bug.
>>>
>>> ORIGINAL POST:
>>>
>>> I came across this issue in some code I was reviewing today where a 
>>> string is converted into a []byte and then a 32 byte slice is taken from 
>>> that and returned. It returns a 32 byte slice even if the string is empty 
>>> or less than 32 bytes in length as long as its not a string literal (comes 
>>> from a function or stored in variable). I can index the slice normally and 
>>> iterate over its elements, but attempting to print it with fmt.Printf 
>>> causes a runtime error where it realizes the capacity is not actually 32. 
>>> Trying to get a slice larger than 32 fails though smaller slices are okay. 
>>> I think that has something to do with the storage needed to describe a 
>>> slice 8 bytes for memory location, 8 bytes for size, 8 bytes for capacity, 
>>> 8 for padding as explained here: 
>>> https://stackoverflow.com/questions/67839752/why-does-an-empty-slice-have-24-bytes
>>>
>>> Here's a playground demo: https://play.golang.com/p/yiLPvRYq8PJ 
>>>
>>> Maybe this is a known issue and or expected behavior so I thought I'd 
>>> ask here before raising an issue on github.
>>>
>>

-- 
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/a8445637-e17c-4b9d-b0bc-b2fe63519e6fn%40googlegroups.com.


[go-nuts] Docker container vscode debugging issue

2023-06-10 Thread Michael Odumosu
Greetings I am trying to debug an open source pacakge hashicorp vault from 
a docker container, I am using vscode remote debugging however its not 
stopping on any of the breakpoints. I tried changing the remote path 
according to this article but no luck, the reason I am debugging hashicorp 
vault is to override the invalid token when you try to set the 
DEV_TOKEN_ROOT_ID to a value that the vault itself would most likely 
create. I need this to happen for a hackathon submission, and the review 
will fail if I cant get this corrected in time. Please assist

-- 
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/3561e79e-7e4e-4a3e-8b08-cb7cfb9f0220n%40googlegroups.com.


[go-nuts] ANN: ficta 1.0.0

2023-05-10 Thread Michael Ellis
I've just released ficta, a small project built using Francisco Escher's 
goopenai package.
https://github.com/Michael-F-Ellis/ficta
Ficta is a command line program that lets you use OpenAI's completion API 
from any text editor.
Ficta exists because I found it frustrating to write short stories and 
essays via the ChatGPT web interface. With ficta, the developing story 
becomes the prompt. ficta also lets you change LLM model and parameters 
freely in mid-stream.


-- 
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/5cace9f2-4d16-4e72-a3bd-59326209348bn%40googlegroups.com.


Re: [go-nuts] Re: Looking for a specialized proxy package

2023-03-15 Thread Michael Ellis
Thanks, Matthew.  I know what RPC is, but have never considered it as a way 
to serve http from behind a NAT.  I should say that the IOT's are part of a 
product that's been in the market for several years.  My client likes the 
web interface we built and wants users to be able to access an IOT's pages 
through a secure intermediary server.  How would that work with grpc?

On Wednesday, March 15, 2023 at 7:08:04 PM UTC-4 Matthew Zimmerman wrote:

> Honestly I'd probably use grpc and keep a constant connection from the IOT 
> to the cloud.  No ports/services required on the client at all and the 
> server can still request things in real time.
>
> Like: 
> https://www.talentica.com/blogs/part-3-building-a-bidirectional-streaming-grpc-service-using-golang/
>
> On Wed, Mar 15, 2023, 6:35 PM Michael Ellis  wrote:
>
>> FWIW,  I pasted my  post into ChatGPT-4 and got what might be a plausible 
>> outline of an approach using httputil.NewSingleHostReverseProxy.
>>
>> But, as we know, LLM's are prone to hallucination. If you're curious, 
>> here's a share link. 
>>
>> https://shareg.pt/cNoNdWc
>>
>> On Wednesday, March 15, 2023 at 5:57:48 PM UTC-4 Michael Ellis wrote:
>>
>>> I posted a question about this on ServerFault 
>>> <https://serverfault.com/questions/1125770/iot-http-multiplexing-through-cloud-host>last
>>>  
>>> week but didn't get any answers other than a few comments from one person 
>>> who said (basically) "use a VPN".   That seems like overkill.  I'm trying 
>>> to find a reliable way to proxy occasional HTTP access to any of  ~100 
>>> geographically dispersed IOT devices through a cloud server.  
>>>
>>> I'm using Go on the cloud server and on the IOT devices, so I thought 
>>> I'd ask here.
>>>
>>> *Situation:*
>>>
>>>- We have complete control over the configuration of the IOT devices 
>>>and the cloud host.
>>>- We don't have control of the customers' routers and firewalls, but 
>>>can specify minimum requirements for port openings, etc.
>>>- FWIW, the IOT devices are BeagleBone Black running Debian Buster 
>>>and the cloud host will be, typically, a multi-core droplet (or similar) 
>>>running Linux.
>>>- The IOT's serve dynamic web pages over HTTP. (HTTPS doesn't seem 
>>>feasible because of certificate requirements and overall load on the IOT 
>>>cpu.) The cloud host will have HTTPS capability.
>>>- This is a low-traffic situation. The IOT's report some overall 
>>>status information (via rsync/ssh) at 4 minute intervals). We already 
>>> have 
>>>a web interface (written in Go) on the cloud server that aggregates and 
>>>displays the status reports.
>>>- Access to an IOT's web service will only occur when a user wants 
>>>to investigate a problem report in more detail. Typically, only one or 
>>> two 
>>>users will have credentials to browse the cloud server.
>>>
>>> The scheme I have in mind is: 
>>>
>>>1. At configuration time for each IOT device the installation tech 
>>>will use ssh-copy-id to install the IOT device's public key on the cloud 
>>>service.
>>>2. The IOT device will  then remotely execute a one-shot program 
>>>(already written and tested) on the cloud server.  The IOT will provide 
>>> a 
>>>unique identifier as an argument and the program will return a permanent 
>>>port number and add a record to a database to record the assignment.
>>>3. The IOT will open a reverse SSH tunnel on the server (probably 
>>>managed by auto-ssh) specifying the permanent port on the server and a 
>>>local port on which it will listen for HTTP requests.
>>>4. The cloud server, when generating status report pages, will 
>>>include a link to fetch the home page of each IOT device by embedding 
>>> its 
>>>unique identifier specified in step 2 above.
>>>
>>> The piece I'm missing is how to construct a proxying handler that will 
>>> use the identifier in the link to look up the tunnel port and fetch the 
>>> IOT's home page and thereafter make it seem as though the user is directly 
>>> browsing the IOT.
>>>
>>> Any help appreciated (and thanks for reading this far!)
>>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "golang-nuts" group.
>> To unsubscribe from this group and stop 

[go-nuts] Re: Looking for a specialized proxy package

2023-03-15 Thread Michael Ellis
FWIW,  I pasted my  post into ChatGPT-4 and got what might be a plausible 
outline of an approach using httputil.NewSingleHostReverseProxy.

But, as we know, LLM's are prone to hallucination. If you're curious, 
here's a share link. 

https://shareg.pt/cNoNdWc

On Wednesday, March 15, 2023 at 5:57:48 PM UTC-4 Michael Ellis wrote:

> I posted a question about this on ServerFault 
> <https://serverfault.com/questions/1125770/iot-http-multiplexing-through-cloud-host>last
>  
> week but didn't get any answers other than a few comments from one person 
> who said (basically) "use a VPN".   That seems like overkill.  I'm trying 
> to find a reliable way to proxy occasional HTTP access to any of  ~100 
> geographically dispersed IOT devices through a cloud server.  
>
> I'm using Go on the cloud server and on the IOT devices, so I thought I'd 
> ask here.
>
> *Situation:*
>
>- We have complete control over the configuration of the IOT devices 
>and the cloud host.
>- We don't have control of the customers' routers and firewalls, but 
>can specify minimum requirements for port openings, etc.
>- FWIW, the IOT devices are BeagleBone Black running Debian Buster and 
>the cloud host will be, typically, a multi-core droplet (or similar) 
>running Linux.
>- The IOT's serve dynamic web pages over HTTP. (HTTPS doesn't seem 
>feasible because of certificate requirements and overall load on the IOT 
>cpu.) The cloud host will have HTTPS capability.
>- This is a low-traffic situation. The IOT's report some overall 
>status information (via rsync/ssh) at 4 minute intervals). We already have 
>a web interface (written in Go) on the cloud server that aggregates and 
>displays the status reports.
>- Access to an IOT's web service will only occur when a user wants to 
>investigate a problem report in more detail. Typically, only one or two 
>users will have credentials to browse the cloud server.
>
> The scheme I have in mind is: 
>
>1. At configuration time for each IOT device the installation tech 
>will use ssh-copy-id to install the IOT device's public key on the cloud 
>service.
>2. The IOT device will  then remotely execute a one-shot program 
>(already written and tested) on the cloud server.  The IOT will provide a 
>unique identifier as an argument and the program will return a permanent 
>port number and add a record to a database to record the assignment.
>3. The IOT will open a reverse SSH tunnel on the server (probably 
>managed by auto-ssh) specifying the permanent port on the server and a 
>local port on which it will listen for HTTP requests.
>4. The cloud server, when generating status report pages, will include 
>a link to fetch the home page of each IOT device by embedding its unique 
>identifier specified in step 2 above.
>
> The piece I'm missing is how to construct a proxying handler that will use 
> the identifier in the link to look up the tunnel port and fetch the IOT's 
> home page and thereafter make it seem as though the user is directly 
> browsing the IOT.
>
> Any help appreciated (and thanks for reading this far!)
>

-- 
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/4eee9142-17f1-4d78-9057-9702e1d2d557n%40googlegroups.com.


[go-nuts] Looking for a specialized proxy package

2023-03-15 Thread Michael Ellis


I posted a question about this on ServerFault 
last
 
week but didn't get any answers other than a few comments from one person 
who said (basically) "use a VPN".   That seems like overkill.  I'm trying 
to find a reliable way to proxy occasional HTTP access to any of  ~100 
geographically dispersed IOT devices through a cloud server.  

I'm using Go on the cloud server and on the IOT devices, so I thought I'd 
ask here.

*Situation:*

   - We have complete control over the configuration of the IOT devices and 
   the cloud host.
   - We don't have control of the customers' routers and firewalls, but can 
   specify minimum requirements for port openings, etc.
   - FWIW, the IOT devices are BeagleBone Black running Debian Buster and 
   the cloud host will be, typically, a multi-core droplet (or similar) 
   running Linux.
   - The IOT's serve dynamic web pages over HTTP. (HTTPS doesn't seem 
   feasible because of certificate requirements and overall load on the IOT 
   cpu.) The cloud host will have HTTPS capability.
   - This is a low-traffic situation. The IOT's report some overall status 
   information (via rsync/ssh) at 4 minute intervals). We already have a web 
   interface (written in Go) on the cloud server that aggregates and displays 
   the status reports.
   - Access to an IOT's web service will only occur when a user wants to 
   investigate a problem report in more detail. Typically, only one or two 
   users will have credentials to browse the cloud server.

The scheme I have in mind is: 

   1. At configuration time for each IOT device the installation tech will 
   use ssh-copy-id to install the IOT device's public key on the cloud service.
   2. The IOT device will  then remotely execute a one-shot program 
   (already written and tested) on the cloud server.  The IOT will provide a 
   unique identifier as an argument and the program will return a permanent 
   port number and add a record to a database to record the assignment.
   3. The IOT will open a reverse SSH tunnel on the server (probably 
   managed by auto-ssh) specifying the permanent port on the server and a 
   local port on which it will listen for HTTP requests.
   4. The cloud server, when generating status report pages, will include a 
   link to fetch the home page of each IOT device by embedding its unique 
   identifier specified in step 2 above.

The piece I'm missing is how to construct a proxying handler that will use 
the identifier in the link to look up the tunnel port and fetch the IOT's 
home page and thereafter make it seem as though the user is directly 
browsing the IOT.

Any help appreciated (and thanks for reading this far!)

-- 
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/116894c3-e90c-4181-9d94-06780724bdf9n%40googlegroups.com.


[go-nuts] Go 1.20 is released

2023-02-01 Thread 'Michael Knyszek' via golang-nuts
Hello gophers,

We have just released Go 1.20.

To find out what has changed in Go 1.20, read the release notes:
https://go.dev/doc/go1.20

You can download binary and source distributions from our download page:
https://go.dev/dl/#go1.20

If you have Go installed already, an easy way to try go1.20
is by using the go command:
$ go install golang.org/dl/go1.20@latest
$ go1.20 download

To compile from source using a Git clone, update to the release with
git checkout go1.20 and build as usual.

Thanks to everyone who contributed to the release!

Cheers,
Michael, Matthew, and Dmitri for the Go team

-- 
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/CAFza%2Bu8Ez40pCa05x%3DgUoB8bG%3DvL1mxspnMs2DyMBnLgp%2B80VA%40mail.gmail.com.


Re: [go-nuts] Create a 1GB ballast but it takes up RSS and pages are Dirty?

2022-11-16 Thread 'Michael Knyszek' via golang-nuts
On Wed, Nov 16, 2022 at 10:19 AM Jie Zhang  wrote:

> Actually, we used go1.16.5 before go1.19 released. Now we're consider
> using go1.19 GOMEMLIMIT instead.
>
> But GOMEMLIMIT is a soft limit, if you deploy multiple services in the
> same host (not per container per service), there will be problems.
> The GC is delayed, and if combined with GOGC=off, the memory usage will be
> higher.
>
In that scenario, I might suggest setting GOGC higher than 100 (not off)
but with some memory limit on each process instead.

>
> Maybe manually trigger forced GC, and combine GOMEMLIMIT will be better.
> I'm testing...
>
Manually triggering GCs has a relatively high risk of hurting performance.
Even if it doesn't hurt performance today, it might in the next release,
unless used very carefully. I don't recommend it outside of testing.

>
> 在2022年11月11日星期五 UTC+8 05:58:54 写道:
>
>> That's correct. The runtime has a simple heuristic for avoiding zeroing
>> but it's far from perfect. As a result, a ballast is inherently always
>> going to be a little risky. This is especially true on some platforms, such
>> as Windows, since there's no way to avoid marking the memory as committed
>> (Windows is free to use demand paging for memory in the range, so overall
>> system memory pressure may increase, but you can't avoid it being
>> *counted* as committed for a particular process).
>>
>> Taking a step back: why a ballast? What about your application makes a
>> ballast a better idea than, for example, setting GOMEMLIMIT= and
>> GOGC=off?
>>
>> (For additional context, back when the memory limit was proposed, so was
>> a memory target (
>> https://go.googlesource.com/proposal/+/master/design/44309-user-configurable-memory-target.md)
>> which more directly replaces a ballast. I found very little interest in
>> this feature.)
>>
>> On Monday, November 7, 2022 at 9:08:23 AM UTC-5 hit.zh...@gmail.com
>> wrote:
>>
>>> Hi, guys, I know what happened.
>>>
>>> When we write `ballast := make([]byte, 1<<30)`, it will call makeslice
>>> to create a new slice. It's a large object. The memory will be allocated
>>> directly via allocLarge() function from heap.
>>>
>>> Actually, after allocating a mspan for it, it will check the address
>>> range whether it should be zeroed. Please check function `func
>>> allocNeedsZero(base, npage uintptr) bool`. When this function returns true,
>>> it means the slice underlying memory will be written to zero, otherwise it
>>> won't write it to zero.
>>>
>>> When we make a ballast as mentioned before, maybe it succeed (no RSS
>>> taken up) or fail (RSS taken up), it's relevant with the return value of
>>> function allocNeedsZero(...). And this function return true or false is
>>> relevant with the arena's state which is affected by previous object
>>> allocation and recycle.
>>>
>>> On Monday, November 7, 2022 at 1:26:41 PM UTC+8 tapi...@gmail.com wrote:
>>>
 I ever also found this problem: global ballast doesn't work.
 So I always use local ballast instead now.

 On Sunday, November 6, 2022 at 8:37:55 PM UTC+8 hit.zh...@gmail.com
 wrote:

> Before, I think the memory is allocated by mmap anon, which Linux OS
> guarantees reading will return zero value and no physical pages allocated.
> When writing happens, the physical pages will be allocated. Then I think
> the create a byte slice maybe the same.
>
> Your idea is clear. I agree with it.
>
> Just now, I use gdb to dump the ballast anon memory and use hexdump to
> check its dirty content, all data is zero (Maybe zeroing happens).
> But after turning GC off, it works as expected (no RSS is taken, no
> DIRTY).
> I think there must be something I didn't get it.
>
> On Sunday, November 6, 2022 at 8:11:51 PM UTC+8 Jan Mercl wrote:
>
>> On Sun, Nov 6, 2022 at 12:54 PM Kn (Kn)  wrote:
>>
>> > Now the problem begins. I expect the ballast like `ballast :=
>> make([]byte, 1<<30)` shouldn't take up any physical memory because 
>> there's
>> no any writing to it.
>>
>> The backing array is specified to be zeroed, so we cannot say there's
>> no writing to it. Depending on the size of the backing array and the
>> operating system it may not get written as an optimization if backed
>> by memory the OS can guarantee to be zero filled. Only then it may
>> remain not yet bound to physical memory.
>>
>> A simple implementation will just zero it, meaning the opposite
>> happens - every byte of the backing array gets written and backing
>> pages for it get allocated.
>>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "golang-nuts" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/golang-nuts/66d0cItfkjY/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion 

Re: [go-nuts] Create a 1GB ballast but it takes up RSS and pages are Dirty?

2022-11-10 Thread 'Michael Knyszek' via golang-nuts
That's correct. The runtime has a simple heuristic for avoiding zeroing but 
it's far from perfect. As a result, a ballast is inherently always going to 
be a little risky. This is especially true on some platforms, such as 
Windows, since there's no way to avoid marking the memory as committed 
(Windows is free to use demand paging for memory in the range, so overall 
system memory pressure may increase, but you can't avoid it being *counted* as 
committed for a particular process).

Taking a step back: why a ballast? What about your application makes a 
ballast a better idea than, for example, setting GOMEMLIMIT= and 
GOGC=off?

(For additional context, back when the memory limit was proposed, so was a 
memory target 
(https://go.googlesource.com/proposal/+/master/design/44309-user-configurable-memory-target.md)
 
which more directly replaces a ballast. I found very little interest in 
this feature.)

On Monday, November 7, 2022 at 9:08:23 AM UTC-5 hit.zh...@gmail.com wrote:

> Hi, guys, I know what happened.
>
> When we write `ballast := make([]byte, 1<<30)`, it will call makeslice to 
> create a new slice. It's a large object. The memory will be allocated 
> directly via allocLarge() function from heap.
>
> Actually, after allocating a mspan for it, it will check the address range 
> whether it should be zeroed. Please check function `func 
> allocNeedsZero(base, npage uintptr) bool`. When this function returns true, 
> it means the slice underlying memory will be written to zero, otherwise it 
> won't write it to zero.
>
> When we make a ballast as mentioned before, maybe it succeed (no RSS taken 
> up) or fail (RSS taken up), it's relevant with the return value of function 
> allocNeedsZero(...). And this function return true or false is relevant 
> with the arena's state which is affected by previous object allocation and 
> recycle.
>
> On Monday, November 7, 2022 at 1:26:41 PM UTC+8 tapi...@gmail.com wrote:
>
>> I ever also found this problem: global ballast doesn't work.
>> So I always use local ballast instead now.
>>
>> On Sunday, November 6, 2022 at 8:37:55 PM UTC+8 hit.zh...@gmail.com 
>> wrote:
>>
>>> Before, I think the memory is allocated by mmap anon, which Linux OS 
>>> guarantees reading will return zero value and no physical pages allocated. 
>>> When writing happens, the physical pages will be allocated. Then I think 
>>> the create a byte slice maybe the same.
>>>
>>> Your idea is clear. I agree with it. 
>>>
>>> Just now, I use gdb to dump the ballast anon memory and use hexdump to 
>>> check its dirty content, all data is zero (Maybe zeroing happens).
>>> But after turning GC off, it works as expected (no RSS is taken, no 
>>> DIRTY). 
>>> I think there must be something I didn't get it.
>>>
>>> On Sunday, November 6, 2022 at 8:11:51 PM UTC+8 Jan Mercl wrote:
>>>
 On Sun, Nov 6, 2022 at 12:54 PM Kn (Kn)  wrote: 

 > Now the problem begins. I expect the ballast like `ballast := 
 make([]byte, 1<<30)` shouldn't take up any physical memory because there's 
 no any writing to it. 

 The backing array is specified to be zeroed, so we cannot say there's 
 no writing to it. Depending on the size of the backing array and the 
 operating system it may not get written as an optimization if backed 
 by memory the OS can guarantee to be zero filled. Only then it may 
 remain not yet bound to physical memory. 

 A simple implementation will just zero it, meaning the opposite 
 happens - every byte of the backing array gets written and backing 
 pages for it get allocated. 

>>>

-- 
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/e3deee3a-5382-4828-bfea-de221fff2175n%40googlegroups.com.


[go-nuts] Re: Facing issues while using builtin functions while executing golang templates

2022-10-20 Thread Michael Ellis
I did a quick search for "is not a defined function".  That message appears 
once in https://go.dev/src/text/template/exec.go.  It's triggered when 
findFunction() fails while executing a template.

Hope that's of some use.


On Wednesday, October 19, 2022 at 8:20:46 AM UTC-4 rit...@ext.dunzo.in 
wrote:

>
> We are facing a strange issue within one of our services where randomly 
> one of the docker containers in production out of (N,  N>50)  starts 
> randomly failing on an API while trying to execute a golang template with 
> an error *"Err: template: : executing \"\" 
> at len: \"len\" is not a defined function".  *`len` is a builtin function 
> within golang so am stumped why this error comes.  Some more context
>
>
>- *Golang Version: 1.15*
>- The same Pod was serving this API and executing the template 
>correctly before this issue started coming
>- Parsing the template works fine, only executing fails. We are 
>parsing and executing in sequence.
>- After this error was encountered first, all subsequent API calls to 
>the same container failed with the same error
>- The same API on all other containers works perfectly fine.  We 
>removed the container from serving prod traffic, and this issue disappeared
>- This is the second time the issue is happening, first time we 
>restarted the container and hence weren't able to debug much
>-  Binary is stripped of symbol tables and ptrace is not enabled
>
> We have the container running (not serving prod traffic) so if there are 
> any hints on how to debug this issue would appreciate.
>

-- 
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/5f252adb-4d0c-4d86-bc61-8b3a47be68d9n%40googlegroups.com.


Re: [go-nuts] How long does it take to import packages?

2022-08-31 Thread 'Michael Pratt' via golang-nuts
Setting GODEBUG=inittrace=1 will log a trace of init function execution,
which you can use to determine if init is slow, and if so which packages.

e.g., `GODEBUG=inittrace=1 go version` ends with "init main @9.5 ms",
indicating that it look 9.5ms to run all init functions.

The format is described at
https://pkg.go.dev/runtime#hdr-Environment_Variables.

On Wed, Aug 31, 2022 at 3:00 AM ag9920  wrote:

> Hi, recently I've been trying to make my unit test faster. It seems too
> much time were spent on initialization. After removing all init() function
> in relevant packages. The speed was still very slow.It even takes dozens of
> seconds before entering my real unit test function.
>
> So I take a look at all the possible factors that might slow down the
> testing. The only possible reason I can think of is the time cost on
> import. Golang needs to import all packages recursively. And in my
> scenario, that's roughly dozens of packages.Maybe initializing const, var
> takes too much time.
>
> Is there any solution that could help me figured out the reason? I didn't
> find any tools that could tell me the time cost on import several packages.
>
> And if that's the case,  import a package does take much time, is it still
> possible for me to speed up my unit test?
>
>
> --
> 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/cd58955e-0c4b-4d56-afd7-1153d7be06dcn%40googlegroups.com
> 
> .
>

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


[go-nuts] Is there FIX exchange trading server or client simulator project with Go

2022-07-23 Thread 'michael yue' via golang-nuts
Is there FIX exchange trading server or client simulator project with Go

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/1f5b47e2-0857-48ea-889a-6cfc4a5b2f14n%40googlegroups.com.


Re: [go-nuts] noinline is 25% faster than inline on apple m1 ?

2022-07-22 Thread 'Michael Pratt' via golang-nuts
I can reproduce similar behavior on linux-amd64:

$ perf stat ./example.com.test -test.bench=BenchmarkInline
-test.benchtime=1x
goos: linux
goarch: amd64
pkg: example.com
cpu: Intel(R) Xeon(R) W-2135 CPU @ 3.70GHz
BenchmarkInline-12  1   16.78 ns/op

PASS

 Performance counter stats for './example.com.test
-test.bench=BenchmarkInline -test.benchtime=1x':

  1,691.95 msec task-clock:u  #1.004 CPUs utilized

 0  context-switches:u#0.000 /sec

 0  cpu-migrations:u  #0.000 /sec

   352  page-faults:u #  208.044 /sec

 6,732,752,072  cycles:u  #3.979 GHz

22,405,823,428  instructions:u#3.33  insn per cycle

 6,501,294,164  branches:u#3.842 G/sec

   149,596  branch-misses:u   #0.00% of all
branches

   1.684677260 seconds time elapsed

   1.692474000 seconds user
   0.00402 seconds sys



$ perf stat ./example.com.test -test.bench=BenchmarkNoInline
-test.benchtime=1x
goos: linux
goarch: amd64
pkg: example.com
cpu: Intel(R) Xeon(R) W-2135 CPU @ 3.70GHz
BenchmarkNoInline-121   10.79 ns/op
PASS

 Performance counter stats for './example.com.test
-test.bench=BenchmarkNoInline -test.benchtime=1x':

  1,091.71 msec task-clock:u  #1.005 CPUs utilized

 0  context-switches:u#0.000 /sec

 0  cpu-migrations:u  #0.000 /sec

   363  page-faults:u #  332.505 /sec

 4,490,159,750  cycles:u  #4.113 GHz

20,205,764,499  instructions:u#4.50  insn per cycle

 6,701,281,015  branches:u#6.138 G/sec

   586,073  branch-misses:u   #0.01% of all
branches

   1.086302272 seconds time elapsed

   1.08771 seconds user
   0.008027000 seconds sys

The non-inlined version is actually fewer instructions to run the same
benchmark, which surprises me because naively looking at the disassembly it
seems that the inlined version is much more compact.


On Fri, Jul 22, 2022 at 5:52 AM eric...@arm.com  wrote:

> For this piece of code, two test functions are the same, but one is
> inlined, the other is not. However the inlined version is about 25% slower
> than the no inlined version on apple m1 chip. Why is it?
>
> The code is here https://go.dev/play/p/0NkLMtTZtv4
>
> --
> 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/527264d7-7cc1-4278-9a29-c04eb3ec4e86n%40googlegroups.com
> 
> .
>

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


[go-nuts] Re: Go allocator: allocates arenas, reclaims pages?

2022-06-20 Thread 'Michael Knyszek' via golang-nuts
Just to clarify, when I said "publicly visible" I meant via blog posts and 
talks. There are a few design 
<https://github.com/golang/proposal/blob/master/design/30333-smarter-scavenging.mdhttps://github.com/golang/proposal/blob/master/design/30333-smarter-scavenging.md>
 
documents 
<https://github.com/golang/proposal/blob/master/design/35112-scaling-the-page-allocator.md#scavenging>
 
and runtime-internal comments 
<https://cs.opensource.google/go/go/+/master:src/runtime/mgcscavenge.go;l=5?q=mgcscavenge.go=go%2Fgo>
 
that go into more depth.

On Monday, June 20, 2022 at 5:46:36 PM UTC-4 Michael Knyszek wrote:

> Thanks for the question. The scavenger isn't as publicly visible as other 
> parts of the runtime. You've got it mostly right, but I'm going to repeat 
> some things you've already said to make it clear what's different.
>
> The Go runtime maps new heap memory (specifically: a new virtual memory 
> mapping for the heap) as read/write in increments called arenas. (Note: my 
> use of "heap" here is a little loose; that pool of memory is also used for 
> e.g. goroutine stacks.) The concept of arena is carried forward to how GC 
> metadata is managed (chunk of metadata per arena) but is otherwise 
> orthogonal to everything else I'm about to describe. To the scavenger, the 
> concept of an arena doesn't really exist.
>
> The platform (OS + architecture) has some underlying physical page size 
> (typically between 4 and 64 KiB, inclusive), but Go has an internal page 
> size of 8 KiB. It divides all of memory up into these 8 KiB pages, 
> including heap memory.
>
> The runtime assumes, in general, that new virtual memory is not backed by 
> physical memory until first use (or an explicit system call on some 
> platforms, like Windows). As free pages get allocated for the heap (for 
> spans, as you say), they are assumed to be backed by physical memory. Once 
> those pages are released, they are still assumed to be backed by physical 
> memory.
>
> This is where the scavenger comes in: it tells the OS that these free 
> regions of the address space, which it assumes are backed by physical 
> pages, are no longer needed in the short term. So, the OS is free to take 
> the physical memory back. "Telling the OS" is the madvise system call on 
> Linux platforms. Note that the Go runtime could be wrong about whether the 
> region is backed by physical memory; that's fine, madvise is just a hint 
> anyway (a really useful one). (Also, it's really unlikely to be wrong, 
> because memory needs to be zeroed before it's handed to the application. 
> Still, it's theoretically possible.)
>
> The scavenger doesn't really have any impact on fragmentation, because the 
> Go runtime is free to allocate a span out of a mix of scavenged and 
> unscavenged pages. When it's actively scavenging, it briefly takes those 
> pages out of the allocation pool, which can affect fragmentation, but the 
> system is organized such that such a collision (and thus potentially some 
> fragmentation) is less likely.
>
> The result is basically just fewer physical pages consumed by Go 
> applications (what "top" reports as "RSS") at the cost of about 1% of total 
> CPU time. The CPU cost, however, is usually much less; 1% is just the 
> target while it's active, but in the steady-state there's typically not too 
> much work to do.
>
> The Go runtime also never unmaps heap memory, because virtual memory 
> that's guaranteed to not be backed by physical memory is very cheap (likely 
> just a single interval in some OS bookkeeping). Unmapping virtual address 
> space is also fairly expensive in comparison to madvise, so it's worthwhile 
> to avoid.
>
> I don't fully understand what you mean by "layered cake" in this context. 
> The memory allocator in general is certainly a "layered cake," but the 
> scavenger just operates directly on the pool of free pages (which again, 
> don't have much to do with arenas other than that happens to be the 
> increment that new pages are added to the pool).
>
> There's also two additional complications to all of this:
> (1) Because the Go runtime's page size doesn't usually match the system's 
> physical page size, the scavenger needs to be careful to only return 
> contiguous and aligned runs of pages that add up to the physical page size. 
> This makes it less effective on platforms with physical page larger than 8 
> KiB because fragmentation can prevent an entire physical page from being 
> free. This is fine, though; the scavenger is most useful when, for example, 
> the heap size shrinks significantly. Then there's almost always a large 
> swathe of available free pages. Note also that platforms with smaller 
&

[go-nuts] Re: Go allocator: allocates arenas, reclaims pages?

2022-06-20 Thread 'Michael Knyszek' via golang-nuts
Thanks for the question. The scavenger isn't as publicly visible as other 
parts of the runtime. You've got it mostly right, but I'm going to repeat 
some things you've already said to make it clear what's different.

The Go runtime maps new heap memory (specifically: a new virtual memory 
mapping for the heap) as read/write in increments called arenas. (Note: my 
use of "heap" here is a little loose; that pool of memory is also used for 
e.g. goroutine stacks.) The concept of arena is carried forward to how GC 
metadata is managed (chunk of metadata per arena) but is otherwise 
orthogonal to everything else I'm about to describe. To the scavenger, the 
concept of an arena doesn't really exist.

The platform (OS + architecture) has some underlying physical page size 
(typically between 4 and 64 KiB, inclusive), but Go has an internal page 
size of 8 KiB. It divides all of memory up into these 8 KiB pages, 
including heap memory.

The runtime assumes, in general, that new virtual memory is not backed by 
physical memory until first use (or an explicit system call on some 
platforms, like Windows). As free pages get allocated for the heap (for 
spans, as you say), they are assumed to be backed by physical memory. Once 
those pages are released, they are still assumed to be backed by physical 
memory.

This is where the scavenger comes in: it tells the OS that these free 
regions of the address space, which it assumes are backed by physical 
pages, are no longer needed in the short term. So, the OS is free to take 
the physical memory back. "Telling the OS" is the madvise system call on 
Linux platforms. Note that the Go runtime could be wrong about whether the 
region is backed by physical memory; that's fine, madvise is just a hint 
anyway (a really useful one). (Also, it's really unlikely to be wrong, 
because memory needs to be zeroed before it's handed to the application. 
Still, it's theoretically possible.)

The scavenger doesn't really have any impact on fragmentation, because the 
Go runtime is free to allocate a span out of a mix of scavenged and 
unscavenged pages. When it's actively scavenging, it briefly takes those 
pages out of the allocation pool, which can affect fragmentation, but the 
system is organized such that such a collision (and thus potentially some 
fragmentation) is less likely.

The result is basically just fewer physical pages consumed by Go 
applications (what "top" reports as "RSS") at the cost of about 1% of total 
CPU time. The CPU cost, however, is usually much less; 1% is just the 
target while it's active, but in the steady-state there's typically not too 
much work to do.

The Go runtime also never unmaps heap memory, because virtual memory that's 
guaranteed to not be backed by physical memory is very cheap (likely just a 
single interval in some OS bookkeeping). Unmapping virtual address space is 
also fairly expensive in comparison to madvise, so it's worthwhile to avoid.

I don't fully understand what you mean by "layered cake" in this context. 
The memory allocator in general is certainly a "layered cake," but the 
scavenger just operates directly on the pool of free pages (which again, 
don't have much to do with arenas other than that happens to be the 
increment that new pages are added to the pool).

There's also two additional complications to all of this:
(1) Because the Go runtime's page size doesn't usually match the system's 
physical page size, the scavenger needs to be careful to only return 
contiguous and aligned runs of pages that add up to the physical page size. 
This makes it less effective on platforms with physical page larger than 8 
KiB because fragmentation can prevent an entire physical page from being 
free. This is fine, though; the scavenger is most useful when, for example, 
the heap size shrinks significantly. Then there's almost always a large 
swathe of available free pages. Note also that platforms with smaller 
physical page sizes are fine, because every scavenge operation releases 
some multiple of physical pages.
(2) The Go runtime tries to take into account transparent huge pages as 
well. That's its own can of worms that I won't go into for now.

On Monday, June 20, 2022 at 11:48:02 AM UTC-4 vitaly...@gmail.com wrote:

> Go allocator requests memory from OS in large arenas (on Linux x86_64 the 
> size of arena is 64Mb), then allocator splits each arena to 8 Kb pages, 
> than merges pages in spans of different sizes (from 8kb to 80kb size 
> according to https://go.dev/src/runtime/sizeclasses.go). This process is 
> well described in various blog posts and presentations. 
>

> But there is much less information about scavenger. Is it true that in 
> contrast to allocation process, scavenger reclaims to OS not arenas, but 
> pages underlying idle spans? This performed with madvice(MADV_DONT_NEED). 
>

>
> If so, Am I correct that after a while the virtual address space of a Go 
> application resembles a "layered cake" of 

Re: [go-nuts] Crash within netpoll.go?

2022-06-08 Thread Michael Sweeney
Thank you. We have since updated our set of services to the GO 1.17.x 
series. Yet, we had an instance of our service deployed using the older 
version. I wish we had the stdout, that would have been useful. I will 
continue to monitor and upgrade. 

Thanks again.
Mike

On Wednesday, June 8, 2022 at 4:55:47 PM UTC-7 Ian Lance Taylor wrote:

> On Wed, Jun 8, 2022 at 4:21 PM Michael Sweeney  wrote:
> >
> > Hi All, I searched around for details and references for a similar error 
> and could not find anything. I am posting here to see if someone has any 
> pointers to help me discover the root cause.
> >
> > A GO 1.15.4 executable encountered a panic and generated a core file. 
> Using 'dlv' to analyze the core file, I found:
> >
> > (dlv) bt
> > 0 0x0047ee01 in internal/poll.runtime_pollOpen
> > at runtime/netpoll.go:144
> > (dlv) frame 0
> > > internal/poll.runtime_pollOpen() runtime/netpoll.go:144 (PC: 0x47ee01)
> > Warning: debugging optimized function
> > Frame 0: runtime/netpoll.go:144 (PC: 47ee01)
> > (dlv) args
> > fd = 0
> > ~r1 = (unreadable empty OP stack)
> > ~r2 = (unreadable empty OP stack)
> >
> > The source code for the above is here:
> >
> > https://github.com/golang/go/blob/go1.15.4/src/runtime/netpoll.go#L144
> >
> > I have used the 'latest' and 1.6.0 of 'delve' both report the same 
> details.
> >
> > Not much else existed. Any suggestions on how one could go about trying 
> to gain more insight into root cause? I have only encountered this once so 
> far.
>
> Normally a panic should print a stack backtrace. Also the line number
> doesn't make sense for a crash. If this problem has only happened
> once, my first guess would be some sort of hardware or kernel failure.
> I personally wouldn't spend more time on this kind of failure unless
> it happens again.
>
> Note that 1.15.4 is no longer supported.
>
> Ian
>

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


[go-nuts] Crash within netpoll.go?

2022-06-08 Thread Michael Sweeney
Hi All, I searched around for details and references for a similar error 
and could not find anything. I am posting here to see if someone has any 
pointers to help me discover the root cause.

A GO 1.15.4 executable encountered a panic and generated a core file. Using 
'dlv' to analyze the core file, I found:

(dlv) bt
0  0x0047ee01 in internal/poll.runtime_pollOpen
   at runtime/netpoll.go:144
(dlv) frame 0
> internal/poll.runtime_pollOpen() runtime/netpoll.go:144 (PC: 0x47ee01)
Warning: debugging optimized function
Frame 0: runtime/netpoll.go:144 (PC: 47ee01)
(dlv) args
fd = 0
~r1 = (unreadable empty OP stack)
~r2 = (unreadable empty OP stack)

The source code for the above is here:

https://github.com/golang/go/blob/go1.15.4/src/runtime/netpoll.go#L144 

I have used the 'latest' and 1.6.0 of 'delve' both report the same details.

Not much else existed. Any suggestions on how one could go about trying to 
gain more insight into root cause? I have only encountered this once so far.

Thanks,
Mike

-- 
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/233670d1-82a2-4902-bfca-867c8543948an%40googlegroups.com.


Re: [go-nuts] Re: Can’t view golang source when clicking on method name in a pkg.go.dev

2022-04-26 Thread 'Michael Pratt' via golang-nuts
This sounds like https://go.dev/issue/48956. In that case, it was some
interference from an extension.

On Tue, Apr 26, 2022 at 4:55 PM Ian Lance Taylor  wrote:

> On Tue, Apr 26, 2022 at 12:40 AM christoph...@gmail.com
>  wrote:
> >
> > This is a screen capture of what I see https://imgur.com/a/nuBfZeY
>
> That's odd.  I don't see that.  And that doesn't look like anything
> that Google would display.  Is it possible that this has something to
> do with the local administration at your site?
>
> Ian
>
> > Le mardi 26 avril 2022 à 09:37:38 UTC+2, christoph...@gmail.com a écrit
> :
> >>
> >> Sorry, my message needs a clarification. The page
> https://cs.opensource.google/go/go/+/go1.18.1:src/encoding/json/stream.go;l=49
> doesn’t show me the source code.
> >> I see a big gray circle with the message, "authorization rejected,
> contact the administrator" which is hopeless of course.
> >>
> >>
> >> Le mardi 26 avril 2022 à 09:16:06 UTC+2, christoph...@gmail.com a
> écrit :
> >>>
> >>> I’m redirected to this page
> https://cs.opensource.google/go/go/+/go1.18.1:src/encoding/json/stream.go;l=49
> when I click on the Decode method in the web page
> https://pkg.go.dev/encoding/json#Decoder.
> >>>
> >>> Is this a transient problem or is the code not open source anymore ?
> >
> > --
> > 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/42a27298-a12f-4276-a23e-ce6bc573d4afn%40googlegroups.com
> .
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/CAOyqgcVQXcrHh19UC40orc%2BMHjzaeSD%2B_LnErp9GycvtaiKM%2BA%40mail.gmail.com
> .
>

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


Re: [go-nuts] Generics faster than native float64?

2022-04-19 Thread Michael Ellis
FWIW, no difference on my  MacBook.

(base) michaels-mbp copybench % go test -bench=.
goos: darwin
goarch: amd64
pkg: localgo/copybench
cpu: Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
BenchmarkCopy-8 6999800   169.4 ns/op
BenchmarkCopyG-86967590   170.6 ns/op
PASS
ok  localgo/copybench2.810s

On Tuesday, April 19, 2022 at 11:06:39 AM UTC-4 peterGo wrote:

> As Ian has pointed out, software and hardware optimizations may distort 
> the results of microbenchmarks.
>
> If I run the original benchmarks using go1.18 and go1.19 the Copy and 
> CopyG ns/op results are reversed.
>
> # Original: https://go.dev/play/p/m1ClnbdbdWi
>
> ~/x$ go1.18 version && go1.18 test x_0_test.go -bench=.
> go version go1.18.1 linux/amd64
> BenchmarkCopy-8 3820009310.7 ns/op
> BenchmarkCopyG-87552230158.3 ns/op
>
> ~/x$ go version && go test x_0_test.go -bench=.
> go version devel go1.19-a11a885cb5 Mon Apr 18 23:57:00 2022 + 
> linux/amd64
> BenchmarkCopy-8 7577499158.2 ns/op
> BenchmarkCopyG-83870822309.7 ns/op
>
> If I run the benchmarks with a ResetTimer() using go1.18 and go1.19 the 
> Copy and CopyG ns/op results are effectively the same.
>
> # ResetTimer: https://go.dev/play/p/hansq5ARrSh
>
> ~/x$ go1.18 version && go1.18 test x_1_test.go -bench=.
> go version go1.18.1 linux/amd64
> BenchmarkCopy-8 7581037158.0 ns/op
> BenchmarkCopyG-87590849157.9 ns/op
>
> ~/x$ go version && go test x_1_test.go -bench=.
> go version devel go1.19-a11a885cb5 Mon Apr 18 23:57:00 2022 + 
> linux/amd64
> BenchmarkCopy-8 7525525158.5 ns/op
> BenchmarkCopyG-87521787158.5 ns/op
>
> If I run the original benchmarks on a Celeron N3450 using go1.18 and 
> go1.19 the Copy and CopyG ns/op results are effectively the same. I run 
> benchmarks on a Celeron N3450 because Intel disables many hardware 
> optimizations on cheap hardware.
>  
> # Original: https://go.dev/play/p/m1ClnbdbdWi
>
> $ go1.18 version && go1.18 test x_0_test.go -bench=.
> go version go1.18.1 linux/amd64
> BenchmarkCopy-4 2773934   428.0 ns/op
> BenchmarkCopyG-42783043   429.7 ns/op
>
> $  go version && go test x_0_test.go -bench=.
> go version devel go1.19-a11a885cb5 Mon Apr 18 23:57:00 2022 + 
> linux/amd64
> BenchmarkCopy-4 2781676   428.6 ns/op
> BenchmarkCopyG-42765179   429.0 ns/op
>
>
> Peter
>
> On Tuesday, April 19, 2022 at 12:37:48 AM UTC-4 Ian Lance Taylor wrote:
>
>> On Mon, Apr 18, 2022 at 1:14 PM Feng Tian  wrote: 
>> > 
>> > Hi, I have the following simple benchmark code, 
>> > 
>> > https://go.dev/play/p/m1ClnbdbdWi 
>> > 
>> > I run this on my laptop since Go playground does not run benchmark 
>> code. The strange thing is that Copy of float64 is slower than copy using 
>> generics. I can imagine generics may add no overhead, but how can it be 
>> faster? 
>> > 
>> > ftian@DESKTOP-16FCU43:~/tmp$ go test -bench=. 
>> > goos: linux 
>> > goarch: amd64 
>> > pkg: a 
>> > cpu: 11th Gen Intel(R) Core(TM) i7-11370H @ 3.30GHz 
>> > BenchmarkCopy-8 5693944 221.7 ns/op 
>> > BenchmarkCopyG-8 8885454 137.1 ns/op 
>> > PASS 
>> > ok a 2.838s 
>>
>> The numbers for this kind of micro-benchmark can be deceptive. For 
>> example, they can be highly affected by alignment of the instruction 
>> loop. I don't know exactly what is happening for you. I compiled the 
>> code with "go test -c" and disassembled it: both benchmark functions 
>> contained exactly the same instructions. 
>>
>> Ian 
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/7b9ca17c-7c52-480d-9efd-ffec453ab12en%40googlegroups.com.


Re: [go-nuts] encoding/json mistakenly transfer int64 format to string

2022-04-14 Thread Michael Ellis
@Brian
That example is a superbly concise explanation go mod. Thanks! And I had no 
idea you could specify filenames and modules in the Playground.  That's 
really useful!

On Wednesday, April 13, 2022 at 3:11:54 AM UTC-4 Brian Candler wrote:

> > I am a little bewildered by  the new mod configuration.
>
> It's as simple as this:
>
> go mod init blah
> go mod tidy
>
> You can put anything(*) for "blah". Literally "blah" will work. It's just 
> whatever name you want to give your module. However if you plan to publish 
> your module on github then using "github.com/name/project" allows it to 
> be found automatically (**).
>
> "go mod tidy" reads through your source code, finds the imported 
> dependencies, and fetches them for you.  After that, a "go build" or "go 
> run" will work.  If you add or remove dependencies, run "go mod tidy" again.
>
> These commands create "go.mod" and "go.sum" files. They become part of 
> your source code - i.e. you should check them in if you are using a source 
> control system.
>
> If you create additional packages in subdirectories, then those packages 
> are referenced in import statements as /. You only need 
> one go.mod at the top level.
> Example: https://go.dev/play/p/GgHLoOuHtUH
>
> HTH,
>
> Brian.
>
> (*) OK, not quite anything: there are some lexical constraints.
> https://go.dev/ref/mod#go-mod-file-ident
> (**) See
> https://go.dev/ref/mod#module-path
>
> On Wednesday, 13 April 2022 at 07:35:13 UTC+1 yan.z...@gmail.com wrote:
>
>> Thank you Steven. 
>> I am a little bewildered by  the new mod configuration. Will it compile 
>> If I download the source file from the new github source to src directory 
>> without further setting up a mod in the old fashioned way? I am using 
>> go1.15.
>>
>> And today I ran a test logging all the sendings to Redis and readings 
>> from Redis. It is fine - nothing went wrong. But 
>> AnotherRedisDesktopManager still shows the same string format - which I 
>> guess is due to it is 32bit and fail to transfer a long decimal to float32.
>>
>> So nothing is wrong in golang or its open-source package.
>>
>> On Tue, Apr 12, 2022 at 9:56 PM Steven Hartland  
>> wrote:
>>
>>> First off, the package you're using for redis isn't maintained; you 
>>> should switch to github.com/gomodule/redigo/redis instead, which will 
>>> allow you to remove the c == nil check as that doesn't happen.
>>>
>>> In your example you're ignoring error from json.Marshal which could be 
>>> hiding a problem, so I would recommend you handle that.
>>>
>>> encoding/json should represent float as a json number so I would never 
>>> expect what you're seeing but its not clear to me if that is down to how 
>>> you are viewing it.
>>>
>>> On Tue, 12 Apr 2022 at 04:02, Zhaoxun Yan  wrote:
>>>
 The scenario is upon receiving an incoming financial quotation, save it 
 as a string of json into a Redis service. Sorry but I cannot provide the 
 whole code of quotation receiving here, which is very complex with cgo. 
 But 
 the code below will help you get a glimpse on what should be going on:

 import (
 "encoding/json"
 //"errors"
 "fmt"
 "time"
 
 "github.com/garyburd/redigo/redis"
 )

 var pool *redis.Pool

 type Fvprices struct {
 P float64 `json:"price"`
 F float64 `json:"floor"`
 C float64 `json:"ceiling"`
 S float64 `json:"settle"`
 T int64   `json:"time"`
 }

 func init() {
 pool = newPool()
 }

 var redisport = "6379"
 var redisip = "127.0.0.1"
 var password = ""

 func newPool() *redis.Pool {

 fmt.Println("redis @", redisport, redisip, password)
 return { 
 MaxIdle: 4,
 MaxActive:   50, // max number of connections
 IdleTimeout: 30 * time.Second,

 Dial: func() (redis.Conn, error) {
 c, err := redis.DialURL("redis://" + redisip + ":" + 
 redisport)
 if err != nil {
 ErrMsg = fmt.Sprintf("redis connection error: %s", err.
 Error())
 fmt.Println(time.Now().Format("2006-01-02 15:04:05"), 
 ErrMsg)
 return nil, err
 }
 if _, autherr := c.Do("AUTH", password); autherr != nil {
 ErrMsg = fmt.Sprintf("redis password error: %s", err.
 Error())
 fmt.Println(time.Now().Format("2006-01-02 15:04:05"), 
 ErrMsg)
 return nil, autherr
 }
 return c, nil
 },
 }
 }

 func Upfutureprice(future_id string,
 future_price, lowerLimitPrice, upperLimitPrice, preSettlementPrice 
 float64,
 updatetime time.Time) {

 c := pool.Get()
 if c == nil {
 return
 }
 defer c.Close()

 content := Fvprices{

Re: [go-nuts] Looked at using Go ... nil/SEGV really bothered me .. Go2 Proposal?

2022-03-25 Thread 'Michael Toy' via golang-nuts
The discussion is quite informative for me to read, thanks for responding. 
Go uses nil in a way which I don't quite yet grok, and so I had no idea if 
it was even a reasonable thing to wish for. Today I am writing in 
Typescript, and the way null is integrated into the type system now (after 
a while) feels natural and helpful to me.

Sam is correct, there is bug in my Go snippet in the post. For humor value 
only, I would like to point out that the imaginary Go compiler I was 
wishing for would have found that bug!

I think Brian gets to the heart of my question, which is "If I really 
understood Go, would I want something like this". I am hearing, "No, you 
would not"

I think if I were to have a long conversation with Axel about "what is it 
that makes programs robust and maintainable" we'd go round in circles a 
bit, as should happen any time you talk about something complex and 
important. I think I disagree with some statements, but even the 
disagreement is super helpful.

Thanks for the discussion!

-Michael Toy

On Thursday, March 24, 2022 at 12:22:44 AM UTC-10 Brian Candler wrote:

> The OP hasn't said specifically which language or feature they're 
> comparing with, but I wonder if they're asking for a pointer type which is 
> never allowed to be nil, enforced at compile time.  If so, a normal 
> pointer-which-may-be-nil would have to be represented as a Maybe[*T] or 
> union { *T | nil }. To use such a pointer value at runtime you'd have to 
> deconstruct it via a case statement or similar, with separate branches for 
> where the value is nil or not-nil. I am sure there have been proposals 
> along those lines floated here before.
>
> I don't think this would negatively affect code readability, because a 
> function which takes *T as an argument can be sure that the value passed in 
> can never be nil (the compiler would not allow a value of type Maybe[*T] to 
> be passed).  Conversely, a function which accepts Maybe[*T] as an argument 
> is explicitly saying that the value passed may legitimately be nil, and 
> hence it needs to check for this.
>
> I like this idea in principle, but in the context of Go it would mean that 
> *T does not have any valid zero value, so you would not be able to use it 
> in any variable or struct which is not explicitly initialized.  This would 
> definitely not be Go any more.
>
> type T 
> var t T  // ok
>
> var p1 Maybe[*T]  // ok
> var p2 *T =   // ok
> var p3 *T  // fails to compile (no zero value is available)
>
> type A struct {
> a Maybe[*T]
> }
> var q1 A // ok
>
> type B struct {
> b *T
> }
> var q2 B = B{b: } // ok
> var q3 B  // fails to compile (cannot create zero-valued instance of this 
> struct, because it includes a member which cannot have a zero value)
>  
> On Thursday, 24 March 2022 at 09:41:23 UTC axel.wa...@googlemail.com 
> wrote:
>
>> One thing to be clear: It is very different if we are talking about "emit 
>> a warning if a value is known to be nil" and "emit a warning unless a 
>> warning is known not to be nil". The former seems fine to me - it is IMO 
>> fine for this code to cause a vet-failure:
>>
>> var x *int
>> y := *x
>>
>> What I'm opposing is the original idea, for this code to cause a 
>> vet-failure:
>>
>> func (x *int) { *x }
>>
>> Importantly, whether or not a value is `nil` is *always* going to be a 
>> heuristic <https://en.wikipedia.org/wiki/Halting_problem>.
>> If we complain about "known to be nil", every finding will always be a 
>> bug. I don't think it's objectionable to find them statically.
>> If we complain about "not known not to be nil", a significant number of 
>> findings will be non-bugs, leading to changes as OP suggested. So, I'm 
>> assuming that's the situation we are talking about.
>>
>> On Thu, Mar 24, 2022 at 9:40 AM Sam Hughes  wrote:
>>
>>> @axel, it my feel counter-intuitive, but a possible runtime panic 
>>> converted to a compiler error is an increase in how robust the code is.
>>>
>>
>> Of course. But that's not what we are talking about. We are converting 
>> *some* runtime bugs into compiler errors (really, vet checks, we can't fail 
>> to compile because of backwards compatibility).
>> But most of them, where it's not clear from the code that a particular 
>> pointer is going to be nil, will get the treatment suggested by OP. Which 
>> ends up exploding the state-space of possible behaviors of a program, 
>> making it exponentially harder to know what it's doing.
>>
>> That's IMO the less intuitive thing. People tend to think "crashing code 
>&

[go-nuts] Looked at using Go ... nil/SEGV really bothered me .. Go2 Proposal?

2022-03-23 Thread 'Michael Toy' via golang-nuts
I barely understand Go, so this is likely a stupid idea. Since Go uses nil 
for a lot of things, lots of things can be nil.

I am not a huge fan of the null safe accessor. 
( https://github.com/golang/go/issues/42847 )

I am a huge fan of the compiler telling me the places where I have not 
checked for nil ... It took me a while to get used to languages which do 
this, but now I can't imagine living without it.

Is it crazy to wish for ...

if x == nil {
  // this does not produce an error because x is known not to be nil
  x.interfaceFunc()
}
// this DOES produce an error/warning if y is possibly nil
y.interfaceFunc()

-- 
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/5a700cd9-9274-4756-80a6-9d322232afebn%40googlegroups.com.


[go-nuts] Constrain a type parameter to be assignable to another

2022-03-16 Thread Michael Andersen
Hi

Is there a way to constrain one parameter to be assignable to another?

For example, in ye olde days, I'd have:

type Iface interface {
// ...
}

type Concrete1 struct { /* ... */ }
var _ Iface = {}

type Concrete2 struct{ /* ... */ }
var _ Iface = {}

// Repeat ad nauseam

Now, I'm finding myself wanting similar compile time checks for generic 
types and functions. E.g.

func foo[Iface any, Concrete Iface]() {
  var c Concrete
  var _ Iface = c
}

Obviously that's a bit contrived, but I'm writing code that needs both the 
concrete type (*someStruct) and the interface it's meant to adhere to.

The above code does not compile with 1.18 (cannot use a type parameter as 
constraint)

I have a runtime check that works, but I'd love a compile time check. Is 
there a way to do that?

Thanks
Michael



-- 
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/c78b9b90-a5e2-4acd-8026-a126805cb643n%40googlegroups.com.


Re: [go-nuts] Generic member of recursive struct

2021-12-20 Thread Michael Ellis
Thanks, Axel & Robert.  As I said in the first post, the package already 
works well for my purposes (and apparently for the few others who use it).  
It allows defining web content more concisely than raw HTML and makes the 
full power of Go available for composing repetitive page structures.

I was mostly just curious about the possibility of detecting bad content at 
compile time instead of at run time. In practice, that's turned out not to 
be a significant problem so I'm ok with learning generics don't support a 
fix.

On Monday, December 20, 2021 at 2:31:32 PM UTC-5 axel.wa...@googlemail.com 
wrote:

> Oh, forgot the footnote:
>
> [1] Note that even that doesn't *actually* work, as `*HtmlNode` would 
> become a parametric type, so it would have to be instantiated to be used in 
> the constraint - you'd have to write `type HtmlNode[T string | 
> *HtmlNode[Something]]`. And the fact that there is no actual answer to what 
> "Something" would be should be a strong indicator for how much generics are 
> not what you want for this.
>
> On Mon, Dec 20, 2021 at 8:29 PM Axel Wagner  
> wrote:
>
>>
>>
>> On Mon, Dec 20, 2021 at 7:07 PM Michael Ellis  
>> wrote:
>>
>>> >Just to be clear, the way I understood you is that you want HtmlTree.C 
>>> to be a slice which has elements which can each either be a string or an 
>>> *HtmlTree - i.e. you want these to be mixed in a single slice. Correct?
>>>
>>> Actually, no.  An HtmlTree instance whose content is a string is a 
>>> terminal node.  The recursion in the Render() func looks like:
>>>
>>>   for _, c := range h.C {
>>> switch c := c.(type) {
>>> case string:
>>> b.WriteString(c)
>>> case *HtmlTree:
>>> err = Render(c, b, rindent)
>>> if err != nil {
>>> return fmt.Errorf("%s : %v", h.T, err)
>>> }
>>> default:
>>> return fmt.Errorf("Bad content %v. Can't render 
>>> type %T! ", h.C, c)
>>> }
>>> }
>>>
>>
>> That's pretty much what I meant, yes. You want a sum type (and in lieu of 
>> sum types, an interface), not generics. 
>> The "union" aspect of Go generics (the `a | b` syntax) only applies to 
>> using interfaces as *constraints*, not as *types* - you want to do the 
>> latter. You want to have a field which is either a string or an *HtmlNode - 
>> but Go only gives you a convenient way to write the two distinct types 
>> `type HtmlNodeString struct { /*…*/ C string }` and `type HtmlNodeNode 
>> struct { /* … */ C *HtmlNode }` into one¹ type declaration and write 
>> function which can work on either. It's just not what you want.
>>
>> The best option for you is (as Robert mentions) to use an interface, 
>> which is an "open sum" - meaning you can't have the guarantee that its 
>> dynamic type is of a limited set of options, but you *can* have a value 
>> whose actual type is dynamic. You can look at e.g. ast.Node 
>> <https://pkg.go.dev/go/ast#Node>, which is de-facto the same thing - 
>> it's supposed to be a limited set of options, but in lieu of sum types, 
>> it's an interface.
>>
>> Go might, at some point, allow the union-elements of constraint 
>> interfaces to be used as actual types, which *would* be a form of sum 
>> types. But probably not for a while - it's more complicated than it may 
>> seem.
>>
>>
>>>
>>> I suppose it's still a problem, though, since the compiler doesn't have 
>>> any way of knowing that's how trees of HtmlTree meant to be constructed. I 
>>> should have expressed the intended constraint on HtmlTree.C as `string | 
>>> []*HtmlTree`.  Does that make a difference?
>>> On Monday, December 20, 2021 at 10:25:26 AM UTC-5 
>>> axel.wa...@googlemail.com wrote:
>>>
>>>> Just to be clear, the way I understood you is that you want HtmlTree.C 
>>>> to be a slice which has elements which can each either be a string or an 
>>>> *HtmlTree - i.e. you wan these to be mixed in a single slice. Correct?
>>>> Because that is not a use case for generics, it's a use case for sum 
>>>> types (which Go does not have).
>>>>
>>>> On Mon, Dec 20, 2021 at 4:11 PM Michael Ellis  
>>>> wrote:
>>>>
>>>>> > They can't, sorry.
>>>&

Re: [go-nuts] Generic member of recursive struct

2021-12-20 Thread Michael Ellis


On Monday, December 20, 2021 at 1:33:49 PM UTC-5 ren...@ix.netcom.com wrote:

> You should use interfaces and a “node” type.
>

Hmm, I tried 

type Node interface {
string | []*HtmlTree
}

type HtmlTree struct {
T string // html tagname, e.g. 'head'
A string // zero or more html attributes, e.g 'id=1 class="foo"'
C Node   // a slice of content whose elements may be strings or 
*HtmlTree
empty bool   // set to true for empty tags like 
}

and the compiler said: 
./prog.go:21:8: interface contains type constraints.

(line 21 is the declaration of HtmlTree.C as type Node)

What's the syntax you have in mind?


 

-- 
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/c619d54d-5a69-4828-b10b-771722f8f646n%40googlegroups.com.


Re: [go-nuts] Generic member of recursive struct

2021-12-20 Thread Michael Ellis
>Just to be clear, the way I understood you is that you want HtmlTree.C to 
be a slice which has elements which can each either be a string or an 
*HtmlTree - i.e. you want these to be mixed in a single slice. Correct?

Actually, no.  An HtmlTree instance whose content is a string is a terminal 
node.  The recursion in the Render() func looks like:

  for _, c := range h.C {
switch c := c.(type) {
case string:
b.WriteString(c)
case *HtmlTree:
err = Render(c, b, rindent)
if err != nil {
return fmt.Errorf("%s : %v", h.T, err)
}
default:
return fmt.Errorf("Bad content %v. Can't render 
type %T! ", h.C, c)
}
}

I suppose it's still a problem, though, since the compiler doesn't have any 
way of knowing that's how trees of HtmlTree meant to be constructed. I 
should have expressed the intended constraint on HtmlTree.C as `string | 
[]*HtmlTree`.  Does that make a difference?
On Monday, December 20, 2021 at 10:25:26 AM UTC-5 axel.wa...@googlemail.com 
wrote:

> Just to be clear, the way I understood you is that you want HtmlTree.C to 
> be a slice which has elements which can each either be a string or an 
> *HtmlTree - i.e. you wan these to be mixed in a single slice. Correct?
> Because that is not a use case for generics, it's a use case for sum types 
> (which Go does not have).
>
> On Mon, Dec 20, 2021 at 4:11 PM Michael Ellis  
> wrote:
>
>> > They can't, sorry.
>> Ok. Thanks, Axel. 
>> Saves me wasting more time.  In the past 3 years of using Go, this is the 
>> only use case where I've  really wanted generics (other cases I've 
>> encountered so far are easily handled with code generation). 
>>
>> -- 
>>
> 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.
>>
> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/golang-nuts/ac75dc32-733d-4a73-9735-619c33cb4cd4n%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/ac75dc32-733d-4a73-9735-619c33cb4cd4n%40googlegroups.com?utm_medium=email_source=footer>
>> .
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/2de22684-0263-465c-8ac0-ff288c535fb7n%40googlegroups.com.


Re: [go-nuts] Generic member of recursive struct

2021-12-20 Thread Michael Ellis
> They can't, sorry.
Ok. Thanks, Axel. 
Saves me wasting more time.  In the past 3 years of using Go, this is the 
only use case where I've  really wanted generics (other cases I've 
encountered so far are easily handled with code generation). 

-- 
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/ac75dc32-733d-4a73-9735-619c33cb4cd4n%40googlegroups.com.


[go-nuts] Generic member of recursive struct

2021-12-20 Thread Michael Ellis
I've got a package, github.com/Michael-F-Ellis/goht, that supports creating 
HTML docs in Go.  It works well, for my purposes at least, but I've always 
been bothered by having to use []interface{} to define the struct member, 
C, that supports recursion.

type HtmlTree struct {
T string// html tagname, e.g. 'head'
A string// zero or more html attributes, e.g 'id=1 
class="foo"'
C []interface{} // a slice of content whose elements may be 
strings or *HtmlTree
empty bool  // set to true for empty tags like 
}

I've created a minimal extract of the package on the playground at 
https://go.dev/play/p/-_7JKRZYLC_J?v=gotip.  Assuming the new generics can 
support constraining HtmlTree.C to be a slice of string | *HtmlTree, what 
is the right syntax for doing so?

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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/a8817b41-85dd-4fd1-a946-00764713c008n%40googlegroups.com.


[go-nuts] Re: Do you have a minimal runnable go code that contain all key words in go?

2021-12-06 Thread Michael Ellis
Nice! Noticed it didn't have "new" so I changed the counter initializer in 
main() from

var c = counter

to 

p := new(counter)
var c = *p

https://go.dev/play/p/2vw4w44qSWm


On Sunday, December 5, 2021 at 4:10:54 PM UTC-5 ben...@gmail.com wrote:

> Not strictly "minimal" -- it uses some keywords twice, and I'm sure it's 
> longer than it needs to be, but here you go: 
> https://go.dev/play/p/XPoqfI8RmyH
>
> On Monday, December 6, 2021 at 4:54:04 AM UTC+13 cuiw...@gmail.com wrote:
>
>> show me you code
>
>

-- 
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/851b403a-dc73-487f-b10e-e1608cb8cda2n%40googlegroups.com.


[go-nuts] Go 1.17.4 and Go 1.16.11 are released

2021-12-02 Thread Michael Knyszek
Hello gophers,

We have just released Go versions 1.17.4 and 1.16.11, minor point releases.

View the release notes for more information:
https://go.dev/doc/devel/release#go1.17.minor

You can download binary and source distributions from the Go web site:
https://go.dev/dl/

To compile from source using a Git clone, update to the release with
"git checkout go1.17.4" and build as usual.

Thanks to everyone who contributed to the releases.

Cheers,
Michael, Heschi, Dmitri, and Carlos for the Go team

-- 
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/CAN%3D%2BcNrpFGMQwHQW-yVt3htHfahHzCe8NNDr9aR282UrJ8c9YQ%40mail.gmail.com.


Re: [go-nuts] Which error handling pattern do you prefer?

2021-11-12 Thread Michael Ellis
FWIW (which may not be much) I've settled on explicitly naming my return 
values in the function declaration.  If the function returns include an 
error, I name always name it err. The general pattern is

func foo() (v someType, err error) {
  err = doSomething()
  if err != nil {
err = fmt.Errorf("some context: %v", err)
return
}
  err = doNextThing()
  if err != nil {
 err = fmt.Errorf("some context: %v", err)
 return
  }
// etc
return
}

Naming the error solves the initial := problem.  As for shadowing, I make 
it a point never to do a := assignment involving err. For example, if I 
need to call os.Open, I do

var f *os.File
f, err = os.Open(...)

I tend to use other names for errors only when it's something I can fix 
within the local scope.

At first I tried hard to avoid the verbosity.  Now I use a few helpful 
snippets to reduce keystrokes and an editor plugin the partially fades any 
block that starts with "if err != nil".  The latter works amazingly well 
(for me at least) to reduce visual clutter.  I like it much better than one 
I tried that auto-folds error blocks.  It made me waste time unfolding them 
to see what was inside :-)

YMMV, of course.

On Friday, November 12, 2021 at 11:15:21 AM UTC-5 david@gmail.com wrote:

> On Fri, Nov 12, 2021 at 7:48 AM Miguel Angel Rivera Notararigo <
> ntr...@gmail.com> wrote:
>
>> I tend to use errX (X is adapted according to context) for function 
>> scoped errors, and err for block scoped errors
>>
>> func MyFunc() error {
>>>   v, errDS := doSomething()
>>>   ...
>>>   errDA := doAnotherthing()
>>> }
>>>
>>
>> if err := doAnotherthing(); err != nil {
>>> return err
>>> }
>>>
>>
>> That way you don't shadow errors.
>>
>
>
> I can't +1 this enough.
>
> I've caught *so* many bugs from shadowed errors (and re-used error 
> variables). I consider it a rather bad anti-pattern to have a single err 
> variable 
> that's reused throughout a scope.
> If you have unique error variable names and you forget to do something 
> with an error that you've assigned a name you automatically get unused 
> variable compile-errors. (just this is enough to be worthwhile)
>
>
> With that said, constraining the scope using the initializer statement on 
> an if (or switch) statement suffices when you don't need any other return 
> values, at which point I may use the err variable-name (although I often 
> make those unique for clarity anyway).
>
>> -- 
>> 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.
>>
> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/golang-nuts/CAF9DLCmR4ZdnVs4A28BSrPcbiHsQ_ufub5cSPjCt2SDy2dA1xA%40mail.gmail.com
>>  
>> 
>> .
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/6b493efc-79ad-43f7-8730-91abd9b6c9cfn%40googlegroups.com.


Re: [go-nuts] initialization loop ?

2021-10-23 Thread Michael Ellis
> The rules for when an initialization loop occurs are part of the language 
spec: https://golang.org/ref/spec#Package_initialization.

Thanks for the link.  It helps with questions I've had recently about 
package initialization.  Can you confirm that the statement

"If a package has imports, the imported packages are initialized before 
initializing the package itself. If multiple packages import a package, the 
imported package will be initialized only once"

means that if 
 - package x imports y and z (in that order), and
 - package y imports a
 - package a imports b
 - package z imports b

then b will be initialized during the initialization of y ( and not 
initialized again during the import of z)?

-- 
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/59051b16-7717-4035-9a9e-765dc894cda9n%40googlegroups.com.


[go-nuts] [security] Go 1.17.2 and Go 1.16.9 are released

2021-10-07 Thread Michael Knyszek
Hello gophers,

We have just released Go versions 1.17.2 and 1.16.9, minor point releases.

These minor releases include a security fix according to the new security
policy (#44918 <https://golang.org/issue/44918>).

When invoking functions from WASM modules, built using GOARCH=wasm GOOS=js,
passing very large arguments can cause portions of the module to be
overwritten with data from the arguments.


If using wasm_exec.js to execute WASM modules, users will need to replace
their copy (as described in
https://golang.org/wiki/WebAssembly#getting-started) after rebuilding any
modules.


This is issue #48797 <https://github.com/golang/go/issues/48797> and
CVE-2021-38297. Thanks to Ben Lubar for reporting this issue.


View the release notes for more information:
https://golang.org/doc/devel/release.html#go1.17.minor

You can download binary and source distributions from the Go web site:
https://golang.org/dl/

To compile from source using a Git clone, update to the release with
"git checkout go1.17.2" and build as usual.

Thanks to everyone who contributed to the releases.

Cheers,
Michael and Heschi for the Go team

-- 
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/CAN%3D%2BcNobSW%3DrQF_5LhX%2BnrU4XooL6QbUpvA77qf5R8ybWmGOiQ%40mail.gmail.com.


Re: [go-nuts] Re: Questions about documentation of Go standard library

2021-10-07 Thread Michael Ellis
Kamil,
Have you read https://go.dev/blog/errors-are-values by Rob Pike?  Wrapping 
my head around the concept that an error is simply a value returned from a 
function was tremendously helpful when I had questions along the same lines 
as yours.

-- 
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/724b763c-cd5d-4c9c-83f2-8c08cb739887n%40googlegroups.com.


Re: [go-nuts] Question on handling Data Race

2021-09-11 Thread Michael Dwyer
Kurtis,

I realized this question would arise.
Presently working with an existing code base.
The code presented in the example is a close approximation to what actually 
exists, the only thing changed were the names.
Additionally, I checked the package and the call order is SomeFunc() -> 
Refresh().
So there will be goroutines that will be calling SomFunc(), which will then 
call Refresh().
Looking at the code I can confirm that Refresh() is not called directly 
from this package.

The problem I face is working with the existing code base, identify 
problems, viz., Data Race, look at the code figure out what the best 
solution to fix the proximate problem.

I do agree with your assessment as to why code would be written in the 
manner, in which it now exists.
I do not, at this time, have an answer to this question.

Working with the authors is difficult at best.
Basically, working alone, with assistance, when really needed, from this 
group.

Presently, taking the existing code, and provide the best solution for 
problems without changing present structure.
Which is why I reached out, because the way the code is presently 
structured, trying to figure out if my proposed solution is workable.

I realize this is not ideal code, could be, should be written cleaner.

My question then is this, using the template of the hypothetical code 
presented, knowing that there are going to be several goroutines calling 
this code,
will my proposed solution address the Data Race problem sufficiently?
Have I missed any potential edge cases, that I have not thought through?

I look forward to your reply.

Thank you for your time and patience ...


THANX(MKD).

On Saturday, September 11, 2021 at 8:42:36 PM UTC-4 Kurtis Rader wrote:

> On Sat, Sep 11, 2021 at 5:01 PM Michael Dwyer  
> wrote:
>
>> Presently working on a Data Race and have some questions on how to 
>> proceed.
>> The code example is a hypothetical mock up of the actual code under 
>> review, but is a fair representation.
>>
>> The struct used by both functions is named Foo.
>> In the hypothetical, SomeFunc() reads variable from foo.bar, checking for 
>> nil,
>> if nil SomeFunc() calls a Foo method Refresh().
>> Foo method Refresh() calls function DoSomeCalc() assigned to foo.bar and 
>> returned back to method SomeFunc()
>>
>> The race detector flags the read of foo.bar in method SomeFunc() in the 
>> if statement,
>> and flags the write of foo.bar in method Refresh().
>>
>> The problem I see is that in method SomeFunc() the if statement does a 
>> read,
>> but it too also does an assignment to foo.bar.
>>
>> My initial thought is to add a sync.Lock() at the beginning of method 
>> SomeFunc(),
>> followed by a defer sync.UnLock(),
>> that will be held until method SomeFunc() exists.
>> I state this because method SomeFunc() also does an assignment to 
>> variable foo.bar.
>> So, a sync.RLock() would be insufficient to protect variable foo.bar
>>
>> My only concern is the call to method Refresh(), which also writes to 
>> foo.bar.
>>
>> If my understanding is correct, this should work, because the lock is 
>> initiated in method SomeFunc(), held to the exit of the method.
>> With the call to method Refresh() occurring within method SomeFunc() the 
>> lock should protect variable foo.bar from other goroutines trying to update 
>> this variable.
>>
>> Asking this question to confirm my thought process is correct.
>> If there is an edge case I missed, please advise.
>>
>> func (foo *Foo) SomeFunc() fields.SomeVariable {
>> if foo.bar == nil { <=== Race detector flags this 
>> read
>> foo.bar = foo.ReFresh()
>> }
>> return foo.bar
>> }
>>
>> func (foo *Foo) ReFresh() fields.SomeVariable {
>> foo.bar = DoSomeCalc(foo)   <=== Race detector flags this 
>> write
>> return foo.bar
>> }
>>
>
> I know this is psuedo-code meant to illustrate the relevant aspect of your 
> real code but I don't understand why you're assigning to foo.bar in the 
> ReFresh() method as well as where you invoke this method in SomeFunc(). If 
> that isn't a mistake introduced while writing the simplified example it 
> suggests there are other problems beyond the data race. It also seems like 
> you've omitted some important details about the real program since the race 
> implies that ReFresh() is called from a goroutine other than the one 
> executing SomeFunc().
>
> -- 
> Kurtis Rader
> Caretaker of the exceptional canines Junior and Hank
>

-- 
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/26024074-973b-4ef8-935c-3568147c46bcn%40googlegroups.com.


[go-nuts] Question on handling Data Race

2021-09-11 Thread Michael Dwyer
Presently working on a Data Race and have some questions on how to proceed.
The code example is a hypothetical mock up of the actual code under review, 
but is a fair representation.

The struct used by both functions is named Foo.
In the hypothetical, SomeFunc() reads variable from foo.bar, checking for 
nil,
if nil SomeFunc() calls a Foo method Refresh().
Foo method Refresh() calls function DoSomeCalc() assigned to foo.bar and 
returned back to method SomeFunc()

The race detector flags the read of foo.bar in method SomeFunc() in the if 
statement,
and flags the write of foo.bar in method Refresh().

The problem I see is that in method SomeFunc() the if statement does a read,
but it too also does an assignment to foo.bar.

My initial thought is to add a sync.Lock() at the beginning of method 
SomeFunc(),
followed by a defer sync.UnLock(),
that will be held until method SomeFunc() exists.
I state this because method SomeFunc() also does an assignment to variable 
foo.bar.
So, a sync.RLock() would be insufficient to protect variable foo.bar

My only concern is the call to method Refresh(), which also writes to 
foo.bar.

If my understanding is correct, this should work, because the lock is 
initiated in method SomeFunc(), held to the exit of the method.
With the call to method Refresh() occurring within method SomeFunc() the 
lock should protect variable foo.bar from other goroutines trying to update 
this variable.

Asking this question to confirm my thought process is correct.
If there is an edge case I missed, please advise.

func (foo *Foo) SomeFunc() fields.SomeVariable {
if foo.bar == nil { <=== Race detector flags this 
read
foo.bar = foo.ReFresh()
}
return foo.bar
}

func (foo *Foo) ReFresh() fields.SomeVariable {
foo.bar = DoSomeCalc(foo)   <=== Race detector flags this 
write
return foo.bar
}


THANX(MKD).

-- 
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/7226a9db-1215-411d-b769-56a9f97d34fdn%40googlegroups.com.


Re: [go-nuts] Two consecutive reads from a buffered channel results in deadlock

2021-09-04 Thread Michael Dwyer
Kurtis, thank you for your explanation and for the links, providing more 
detailed information on the subject matter.
This was what I was looking for, a reasoned explanation and documentation 
that would explain why this condition occurred.

Always good when there are those willing to provide helpful hints and 
documentation, so others can learn.

Greatly appreciate your time an assistance.


THANX(MKD).

On Saturday, September 4, 2021 at 9:31:32 PM UTC-4 Kurtis Rader wrote:

> On Sat, Sep 4, 2021 at 5:55 PM Michael Dwyer  wrote:
>
>> I encountered a deadlock when reading from a buffered channel.
>> The deadlock occurs when an attempt is made to read from the channel 
>> twice, without an intermediate write to the channel.
>>
>
> That is not a deadlock. Reading from a buffered channel blocks when the 
> channel is empty. From https://golang.org/ref/spec#Channel_types:
>  
>
> Otherwise, the channel is buffered and communication succeeds without 
> blocking if the buffer is not full (sends) or not empty (receives). A nil 
> channel 
> is never ready for communication.
> You can use the "select" operator (
> https://golang.org/ref/spec#Select_statements) to detect if the channel 
> is empty.
>  
>
>> The problematic code is as follows:
>>
>> func main() {
>> myInt  := 432
>>
>> readerChan := make(chan int, 3)
>>
>> for forI := 0; forI <= 1; forI++ {
>> readerChan <- myInt
>> fmt.Printf("%d:", <- readerChan)
>> fmt.Printf("%d:", <- readerChan)
>> }
>>
>> close(readerChan)
>> }
>>
>> The first read from variable readerChan succeeds.
>> The second read from variable readerChan results in a deadlock.
>>
>> I have two links to playground.
>> The first link is the problematic code.
>> The second link is for similar code that has an intervening write to the 
>> channel.
>>
>> I understand that a buffered channel allows a queue of results to be 
>> stored from other Go routines writing to the channel.
>> But, the code is attempting multiple read operations.
>>
>> Looking for a technical explanation to help me better understand this 
>> particular case.
>> Thanks in advance ...
>>
>>
>> The problematic playground link : https://play.golang.org/p/veo7phAZzMv
>> The working playground link : https://play.golang.org/p/qvYZNN9keqN
>>
>>
>> THANX(MKD).
>>
>> -- 
>> 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.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/golang-nuts/44057a7a-b0aa-4ea1-9fb3-39836cd5713dn%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/44057a7a-b0aa-4ea1-9fb3-39836cd5713dn%40googlegroups.com?utm_medium=email_source=footer>
>> .
>>
>
>
> -- 
> Kurtis Rader
> Caretaker of the exceptional canines Junior and Hank
>

-- 
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/7b41546f-f4cd-4c73-90bc-ee86775431fan%40googlegroups.com.


[go-nuts] Two consecutive reads from a buffered channel results in deadlock

2021-09-04 Thread Michael Dwyer
I encountered a deadlock when reading from a buffered channel.
The deadlock occurs when an attempt is made to read from the channel twice, 
without an intermediate write to the channel.

The problematic code is as follows:

func main() {
myInt  := 432

readerChan := make(chan int, 3)

for forI := 0; forI <= 1; forI++ {
readerChan <- myInt
fmt.Printf("%d:", <- readerChan)
fmt.Printf("%d:", <- readerChan)
}

close(readerChan)
}

The first read from variable readerChan succeeds.
The second read from variable readerChan results in a deadlock.

I have two links to playground.
The first link is the problematic code.
The second link is for similar code that has an intervening write to the 
channel.

I understand that a buffered channel allows a queue of results to be stored 
from other Go routines writing to the channel.
But, the code is attempting multiple read operations.

Looking for a technical explanation to help me better understand this 
particular case.
Thanks in advance ...


The problematic playground link : https://play.golang.org/p/veo7phAZzMv
The working playground link : https://play.golang.org/p/qvYZNN9keqN


THANX(MKD).

-- 
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/44057a7a-b0aa-4ea1-9fb3-39836cd5713dn%40googlegroups.com.


[go-nuts] Re: Printing a slice of structs recursively

2021-09-02 Thread Michael Ellis
Here's one way. https://goplay.space/#5KzrUc0171N

On Thursday, September 2, 2021 at 1:03:48 AM UTC-4 seank...@gmail.com wrote:

> Try doing it recursively, passing in both the current parent id and 
> indentation level
>
> On Thursday, September 2, 2021 at 3:55:01 AM UTC+2 n.erde...@gmail.com 
> wrote:
>
>> i need some help with printing a slice of structs which there is a child 
>> - parent relation in the struct.
>> *type* Emp *struct* {
>> id   int
>> name string
>> parentID int
>> }
>> probably the best way to do it recursively but i couldnt manage to do
>> https://play.golang.org/p/jHcbu3uBgOD
>
>

-- 
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/ae9b334a-67ab-4e5a-a1a6-a4e2a996a3ebn%40googlegroups.com.


Re: [go-nuts] Makefiles for Go Programs

2021-08-23 Thread Michael Ellis
Three cheers for mage .  It's more verbose than make 
but it's pure Go. I use it to build and test projects that include 
generated html/css/js supported by a Web Assembly clients communicating 
with a server.

On Monday, August 23, 2021 at 7:33:10 PM UTC-4 Connor Kuehl wrote:

>
>
> > On Aug 22, 2021, at 10:11 PM, jlfo...@berkeley.edu  
> wrote:
> > 
> > 
> > I've noticed that few, if any, Go programs use Makefiles. Is that 
> because the overhead of using make is greater than the overhead of just 
> always compiling and linking everything?
> > One piece of evidence for this is that the Go compiler leaves no 
> artifacts, like object files, so as is make wouldn't fit into the current 
> build method.
> > 
>
> I started using a Makefile for my Go project so that I could inject a 
> version string at build time without having to remember what to pass to go 
> binaries.
>
> I made a Discord bot to use in a server with my friends, and since I have 
> some automation in place to automatically deploy the tip of my main branch, 
> I thought it’d be convenient to be able to ask the bot what build it’s 
> running so we can see which commits are “live."
>
> So while it’s not a “traditional” use of make, it certainly is convenient.
>
> Connor
>
> P.S., here’s the Makefile. The important bits are the lines that mention 
> “LD_FLAGS"
>
> VERSION := v2.2.0+dev
> BUILD := $(shell git describe --tags 2>/dev/null || echo "$(VERSION)")
>
> LD_FLAGS := "-X 'main.Version=$(BUILD)'"
>
> SOURCES := $(shell find . -type f -name '*.go')
> SOURCES += go.mod go.sum
>
> .PHONY: build clean test
>
> all: popple
>
> popple: build
>
> build: $(SOURCES)
> @go build -v -ldflags=$(LD_FLAGS) ./...
>
> test: popple
> @go test -v -ldflags=$(LD_FLAGS) ./...
>
> clean:
> @rm -rf popple

-- 
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/6b2116b0-b6e1-4d60-bd88-ee71f011035en%40googlegroups.com.


[go-nuts] Go 1.17 is released

2021-08-16 Thread Michael Knyszek
Hello gophers,

We just released Go 1.17

To find out what has changed in Go 1.17, read the release notes:
https://golang.org/doc/go1.17

You can download binary and source distributions from our download page:
https://golang.org/dl/

If you have Go installed already, an easy way to try go1.17
is by using the go command:
$ go get golang.org/dl/go1.17
$ go1.17 download

To compile from source using a Git clone, update to the release with
"git checkout go1.17" and build as usual.

Thanks to everyone who contributed to the release!

Cheers,
Michael and Dmitri for the Go Team

-- 
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/CAN%3D%2BcNqFSAm8Er%3D09Yn825eKB4rgg24ZMvGSp5467ffj1z5Pdw%40mail.gmail.com.


[go-nuts] GOOS=js/GOARCH=wasm

2021-07-27 Thread W. Michael Petullo
I have been building applications using the GOOS=js/GOARCH=wasm for around 
two years. I really like being able to write both client and server code in 
Go. I have four questions that I have not yet found a clear answer for:

(1) The syscall/js package is marked EXPERIMENTAL. Is there any consensus 
as to when this package might become stable?

(2) The rules surrounding Go routines are different from the expectations 
of Go itself. There is a comment in src/syscall/js/func.go concerning this:

// As a consequence, if one wrapped function blocks, JavaScript's event loop 
// is blocked until that function returns. Hence, calling any async 
JavaScript 
// API, which requires the event loop, like fetch (http.Client), will cause 
an 
// immediate deadlock. Therefore a blocking function should explicitly 
start a 
// new goroutine. 

Is this the expected behavior in the long term? I often get caught up in 
the rules here.

(3) I have not yet found a clean way to read a file from the browser (i.e., 
in response to a file HTML input). I presently use a JavaScript function 
that uses a FileReader to read the file into a global variable data before 
setting another global Boolean done to true. On the Go side, I poll the 
global Boolean done, waiting for it to become true before pulling the file 
out of the global data. Does anyone have an example of a better way to do 
this?

(4) I have a Wasm Go routine that updates a progress bar as it executes. 
However, the progress bar does not update until the Go routine completes. I 
suspect this is related to (2). Is there a pattern for getting this to work?

--
Mike

:wq

-- 
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/e568cb0c-c9a9-4155-ae30-ea29fb7f2ea9n%40googlegroups.com.


Re: [go-nuts] Go and GPUs

2021-06-25 Thread Michael Poole
On Fri, Jun 25, 2021 at 11:52 AM Nikolay Dubina wrote:
>
> I tried to write down my own CUDA / NVIDIA GPU driver in native Go last 
> weekend. To my great surprise, CUDA and pretty much all high performance 
> software/hardware from NVIDIA is proprietary close-source C/C++ code. 
> Meaning, you can't write native Go driver even if you wanted to. Forget Go, 
> people are trying to reverse engineer it in C/C++ with limited success. From 
> what I heard OpenCV is not a priority for NVIDIA either. Then I looked up 
> what Apple is doing with their Neural Engine in latest chips. It too is 
> closed-source Objective-C, Swift. I suspect situation with other powerful 
> hardware is the same. Moore's law seem to be about GPU lately, and everyone 
> is locking it in. Kind of not in the spirit open-source and Linux. That's 
> quite bad state of affairs for Go and computing in general. Yikes!
>
> Just want to see what others are thinking.

That would be a very nice thing to have.  I see four basic areas where
this becomes tricky or requires a lot of work.

1) Getting memory management right for sharing with the accelerator
device.  Shared memory buffers need to stay locked for longer than
just the call to a library or to the OS kernel, but in the worse case
could use something like Manish Rai Jain of Dgraph described at
https://dgraph.io/blog/post/manual-memory-management-golang-jemalloc/
.  A lot of Nvidia's recent CUDA programmer-productivity improvements
have focused around transparent data movement, and Go's garbage
collector probably breaks the assumptions for those.

2) "Friendly" source development (like CUDA C) integrates the host and
target code into a single code base, with some kind of markup or
compiler hint about which functions should be compiled for the
accelerator, and which function calls need to be treated specially.
Those "special" function calls must be translated to dispatch the call
(usually with additional arguments like the grid/NDRange parameters)
to the accelerator rather than as a normal function call.  This is a
compiler front-end problem, which is almost certainly a lot easier
with Go than with C or C++, but still requires attention and perhaps
considerable effort because it requires multiple back-ends to run for
some functions.  In the worst case, do like OpenCL and require the
programmer to provide or build strings containing program text, along
with verbose code to set up calls to the accelerator.

3) Generating code for the accelerator.  SPIR-V is an obvious
candidate for portable uses; it integrates reasonably with current
OpenCL as well as Vulkan.  Nvidia makes a reasonable compromise for
this with their PTX assembly pseudo-language: They have good
documentation about which PTX instructions are only supported on some
GPU generations, they document when the translation to actual machine
code varies in major ways, and they even have a decent API for
compiling application-provided PTX code.  This is a compiler back-end
problem, conditional on not accepting the "worst case" in #2 above.

4) Integrating target libraries with the rest of an application.  A
large part of the value proposition for CUDA is that it has a lot of
highly optimized libraries available out of the box: cuFFT,
cuBLAS/NVBLAS, and more.  These are a hybrid between GPU elements and
host elements, and a lot of the host elements end up being black boxes
with respect to other languages.  The most general fix is to call out
to C, which is not satisfying for portability.

If I were going to spend the time on this, I would probably target
SPIR-V with Vulkan or OpenCL for portability rather than Nvidia's PTX
or Apple's Metal.  AMD, Nvidia and Google (Android) all have good
support for SPIR-V through their Vulkan stacks, and there are
third-party Vulkan layers that run on MacOS.

- Michael Poole

-- 
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/CAOU-OAK3dUn0hDAvEt3ayhQO4Ryg2-bMpaKZTCxW086%2BYFFnpQ%40mail.gmail.com.


Re: [go-nuts] How to cast a multi-value?

2021-05-18 Thread 'Marc Michael' via golang-nuts
'Keith Randall' via golang-nuts  schrieb am
Di., 18. Mai 2021, 18:25:

> You can use a function call to do the cast:
>
> func byteErr2stringErr(b []byte, e error) (string, error) {
> return string(b), e
> }
> content, err := byteErr2stringErr(os.ReadFile(path))
>
> It's still using additional variables, but they are hidden inside the
> helper function.
> On Sunday, May 16, 2021 at 8:07:24 PM UTC-7 Kurtis Rader wrote:
>
>> On Sun, May 16, 2021 at 7:49 PM 'Marc Michael' via golang-nuts <
>> golan...@googlegroups.com> wrote:
>>
>>> as Go provides multi values I would expect that's possible to cast such
>>> a multi value. Do I see it correctly, that Go does not provide it?
>>>
>>> Example:
>>>
>>> os.ReadFile returns []byte, error.
>>> I want to cast the []byte to a string.
>>>
>>> content, err := os.ReadFile(path)
>>>
>>> Is it possible to cast the []byte directly to a string without using a
>>> second variable?
>>>
>>
>> No, it is not possible to transform the type of one return value in a 
>> multi-valued
>> expression such as a function call. Such syntactic sugar would have limited
>> usefulness and, in my opinion, is likely to decrease readability and thus
>> be a source of bugs. If you find yourself needing to perform such
>> conversions so often that such a feature is useful that suggests the APIs
>> you're using need to be changed.
>>
>
Hello,

thanks for the clarification. I have thought that I had something overseen.

I have thought about introducing a second variable of type string, but this
would lead to doubling of the memory usage, especaly as I don't now really
how much data there is. With the additional function I think this would not
a real problem, as the []byte would go away if the additional function
finishes.

Thanks all for your help. :-)

Kindly regards

>

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


[go-nuts] How to cast a multi-value?

2021-05-16 Thread 'Marc Michael' via golang-nuts
Hello,

as Go provides multi values I would expect that's possible to cast such a
multi value. Do I see it correctly, that Go does not provide it?

Example:

os.ReadFile returns []byte, error.
I want to cast the []byte to a string.

content, err := os.ReadFile(path)

Is it possible to cast the []byte directly to a string without using a
second variable?

Kindly regards

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAEOc3dWn%3Dn%3DFNaQVhnu56yu9yaoVeJRin_m%2B7DNh8hvqV7Ck%2Bw%40mail.gmail.com.


Re: [go-nuts] Syscalls that take structs with embedded pointers

2021-05-14 Thread 'Michael Pratt' via golang-nuts
Go has a non-moving GC [1], so that is not an issue. That said,
unsafe.Pointer states "the referenced allocated object, if any, is retained
and not moved until the call completes". It doesn't say that this
recursively applies to objects referenced by the converted object, though I
perhaps it should.

[1] Except for stacks, but taking the address of a byte slice and putting
it in Iovec.Base will force it to escape anyways.

On Fri, May 14, 2021 at 9:44 AM Shaun Crampton  wrote:

> > You can use a *byte for the buffer. For instance, unix.Iovec does this
>
> Are you sure that's not a bug?  What's to stop the *Byte from being
> moved by the GC?
>
> On Fri, May 14, 2021 at 2:27 PM Michael Pratt  wrote:
> >
> > You can use a *byte for the buffer. For instance, unix.Iovec does this:
> https://pkg.go.dev/golang.org/x/sys/unix#Iovec
> >
> > Users can cast a *unix.Iovec directly to unsafe.Pointer for Syscall
> without any special handling of the *byte field.
> >
> > On Fri, May 14, 2021, 09:01 sh...@tigera.io  wrote:
> >>
> >> Now, is it technically legal to convert a uintptr to some location that
> was manually allocated and then cast it to an unsafe.Pointer?  When I look
> at the docs for unsafe.Pointer, I can't match that to any of the cases but
> it seems very likely to be safe by analogy with the GCO rules for handling
> "C" pointers and "Go" pointers.
> >>
> >> On Friday, May 14, 2021 at 1:24:28 PM UTC+1 sh...@tigera.io wrote:
> >>>
> >>> Thanks for the pointer to that package; looking at our go.mod, looks
> like we've already got it as a transitive dependency so it looks ideal for
> my use case.
> >>>
> >>> On Friday, May 14, 2021 at 12:10:45 PM UTC+1 Jan Mercl wrote:
> >>>>
> >>>> On Fri, May 14, 2021 at 12:36 PM sh...@tigera.io 
> wrote:
> >>>>
> >>>> > One way I could see to solve this would be to do some manual memory
> management with MMap or BRK to allocate the buffer but I wondered if there
> was an easier way?
> >>>>
> >>>> IMO using manual memory management _is_ the easy way in this case. I'm
> >>>> using https://pkg.go.dev/modernc.org/memory for 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.
> >> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/317d44cf-8f2b-42d6-ab10-b42da7280616n%40googlegroups.com
> .
>

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


Re: [go-nuts] Syscalls that take structs with embedded pointers

2021-05-14 Thread 'Michael Pratt' via golang-nuts
You can use a *byte for the buffer. For instance, unix.Iovec does this:
https://pkg.go.dev/golang.org/x/sys/unix#Iovec

Users can cast a *unix.Iovec directly to unsafe.Pointer for Syscall without
any special handling of the *byte field.

On Fri, May 14, 2021, 09:01 sh...@tigera.io  wrote:

> Now, is it technically legal to convert a uintptr to some location that
> was manually allocated and then cast it to an unsafe.Pointer?  When I look
> at the docs for unsafe.Pointer, I can't match that to any of the cases but
> it seems very likely to be safe by analogy with the GCO rules for handling
> "C" pointers and "Go" pointers.
>
> On Friday, May 14, 2021 at 1:24:28 PM UTC+1 sh...@tigera.io wrote:
>
>> Thanks for the pointer to that package; looking at our go.mod, looks like
>> we've already got it as a transitive dependency so it looks ideal for my
>> use case.
>>
>> On Friday, May 14, 2021 at 12:10:45 PM UTC+1 Jan Mercl wrote:
>>
>>> On Fri, May 14, 2021 at 12:36 PM sh...@tigera.io 
>>> wrote:
>>>
>>> > One way I could see to solve this would be to do some manual memory
>>> management with MMap or BRK to allocate the buffer but I wondered if there
>>> was an easier way?
>>>
>>> IMO using manual memory management _is_ the easy way in this case. I'm
>>> using https://pkg.go.dev/modernc.org/memory for 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.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/317d44cf-8f2b-42d6-ab10-b42da7280616n%40googlegroups.com
> 
> .
>

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


Re: [go-nuts] TotalAlloc dropped in runtime/metrics

2021-04-29 Thread 'Michael Knyszek' via golang-nuts
Hi Marco, https://go-review.googlesource.com/c/go/+/312431 just landed and
should resolve the issue for Go 1.17.

On Tue, Apr 20, 2021 at 3:28 PM Michael Knyszek  wrote:

> Oh, actually, you can compute Mallocs and Frees from allocs-by-size and
> frees-by-size (summing the total # of samples). You can only estimate
> TotalAlloc though, which is genuinely missing.
>
> On Tue, Apr 20, 2021 at 3:14 PM Michael Knyszek 
> wrote:
>
>> Oh gosh, I think TotalAlloc, Mallocs, and Frees are actually an oversight
>> on my part. Sorry about that. They're very easy to add and I can probably
>> even add them for this release.
>>
>> Please do use the new runtime/metrics package!
>>
>> Most of the other metrics should be there in some form (e.g. the
>> divisions are a little different; they're meant to be more orthogonal to
>> each other... GC pause latencies are now in a histogram) and new ones are
>> going to be added in the next release and in the future. Also: today, it
>> does not have the same stop-the-world penalty that ReadMemStats has, so I
>> recommend it on that basis.
>>
>> On Tue, Apr 20, 2021 at 3:08 PM Ian Lance Taylor  wrote:
>>
>>> [ + mknyszek ]
>>>
>>> On Tue, Apr 20, 2021 at 11:12 AM Marco A.  wrote:
>>> >
>>> > Hi everyone,
>>> >
>>> > I was considering using the new stable metrics interface with go 1.16 (
>>> https://golang.org/pkg/runtime/metrics/) for our program and I was also
>>> wondering why things like TotalAlloc (
>>> https://golang.org/pkg/runtime/#MemStats) had been dropped in the
>>> available metrics.
>>> >
>>> > Any particular reasoning behind 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.
>>> > To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/golang-nuts/c12d3534-d0b3-4567-9bc8-7cdcfb63c23cn%40googlegroups.com
>>> .
>>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAFza%2Bu_SZRSpeEBHJ904jChgs%3D_Fu_ws8EGG8Zwh2jd174BmLg%40mail.gmail.com.


Re: [go-nuts] Re: How to do vdso calls in my own code?

2021-04-27 Thread 'Michael Pratt' via golang-nuts
Oops, I should say the syscall package could do this. x/sys/unix has the
extra complexity of not being tied to a Go release.

On Tue, Apr 27, 2021, 12:53 Michael Pratt  wrote:

> I'm not sure if calling through the VDSO is the best solution to this
> specific issue, though it does sound like a case that would certainly
> benefit.
>
> Regardless, one fairly clean way we could support this would be to make
> x/sys/unix.ClockGettime (and Gettimeofday) call through the VDSO rather
> than performing the syscall. That is always a valid operation (the VDSO
> will make the syscall if it doesn't support the specific options passed),
> and I think would solve this problem without even changing the API. It
> seems we don't do that already for simplicity of implementation and prior
> lack of need.
>
> On Tue, Apr 27, 2021 at 12:13 PM Ian Lance Taylor  wrote:
>
>> On Tue, Apr 27, 2021, 8:55 AM Manlio Perillo 
>> wrote:
>>
>>> Il giorno martedì 27 aprile 2021 alle 17:51:46 UTC+2 Ian Lance Taylor ha
>>> scritto:
>>>
>>>> On Tue, Apr 27, 2021 at 7:43 AM Manlio Perillo 
>>>> wrote:
>>>> >
>>>> > Il giorno lunedì 26 aprile 2021 alle 10:24:09 UTC+2 Pure White ha
>>>> scritto:
>>>> >>
>>>> >> So I really want to know what is the right way to do vdso call
>>>> outside runtime?
>>>> >>
>>>> > What about using a different function instead of time.Now, and using
>>>> RawSyscall?
>>>>
>>>> That wouldn't be a VDSO call. VDSO calls are in general faster than
>>>> system calls. There is more background at
>>>> https://man7.org/linux/man-pages/man7/vdso.7.html.
>>>
>>> Ian
>>>
>>>
>>> Yes, that wouldn't a VDSO call.  But since a VDSO call will require cgo
>>> , maybe RawSyscall will be more efficient?
>>>
>>
>> The meaningful comparison is to time.Now, which uses VDSO.  I suppose it
>> is possible that RawSyscall of clock_gettime with a coarse clock would be
>> faster than time.Now, but I would be surprised.
>>
>> Ian
>>
>>> --
>> You received this message because you are subscribed to the Google Groups
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to golang-nuts+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/golang-nuts/CAOyqgcX9mfSFq5gucrTCi0PJyVdLzA2xGXNByDeOGOyaFLo1hA%40mail.gmail.com
>> <https://groups.google.com/d/msgid/golang-nuts/CAOyqgcX9mfSFq5gucrTCi0PJyVdLzA2xGXNByDeOGOyaFLo1hA%40mail.gmail.com?utm_medium=email_source=footer>
>> .
>>
>

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


Re: [go-nuts] Re: How to do vdso calls in my own code?

2021-04-27 Thread 'Michael Pratt' via golang-nuts
I'm not sure if calling through the VDSO is the best solution to this
specific issue, though it does sound like a case that would certainly
benefit.

Regardless, one fairly clean way we could support this would be to make
x/sys/unix.ClockGettime (and Gettimeofday) call through the VDSO rather
than performing the syscall. That is always a valid operation (the VDSO
will make the syscall if it doesn't support the specific options passed),
and I think would solve this problem without even changing the API. It
seems we don't do that already for simplicity of implementation and prior
lack of need.

On Tue, Apr 27, 2021 at 12:13 PM Ian Lance Taylor  wrote:

> On Tue, Apr 27, 2021, 8:55 AM Manlio Perillo 
> wrote:
>
>> Il giorno martedì 27 aprile 2021 alle 17:51:46 UTC+2 Ian Lance Taylor ha
>> scritto:
>>
>>> On Tue, Apr 27, 2021 at 7:43 AM Manlio Perillo 
>>> wrote:
>>> >
>>> > Il giorno lunedì 26 aprile 2021 alle 10:24:09 UTC+2 Pure White ha
>>> scritto:
>>> >>
>>> >> So I really want to know what is the right way to do vdso call
>>> outside runtime?
>>> >>
>>> > What about using a different function instead of time.Now, and using
>>> RawSyscall?
>>>
>>> That wouldn't be a VDSO call. VDSO calls are in general faster than
>>> system calls. There is more background at
>>> https://man7.org/linux/man-pages/man7/vdso.7.html.
>>
>> Ian
>>
>>
>> Yes, that wouldn't a VDSO call.  But since a VDSO call will require cgo ,
>> maybe RawSyscall will be more efficient?
>>
>
> The meaningful comparison is to time.Now, which uses VDSO.  I suppose it
> is possible that RawSyscall of clock_gettime with a coarse clock would be
> faster than time.Now, but I would be surprised.
>
> Ian
>
>> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/CAOyqgcX9mfSFq5gucrTCi0PJyVdLzA2xGXNByDeOGOyaFLo1hA%40mail.gmail.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CALoThU-sH_HvNbZz-NSR-OOa3tZNybw2YNYK43YqWsYkmT-XsA%40mail.gmail.com.


Re: [go-nuts] TotalAlloc dropped in runtime/metrics

2021-04-20 Thread 'Michael Knyszek' via golang-nuts
Oh, actually, you can compute Mallocs and Frees from allocs-by-size and
frees-by-size (summing the total # of samples). You can only estimate
TotalAlloc though, which is genuinely missing.

On Tue, Apr 20, 2021 at 3:14 PM Michael Knyszek  wrote:

> Oh gosh, I think TotalAlloc, Mallocs, and Frees are actually an oversight
> on my part. Sorry about that. They're very easy to add and I can probably
> even add them for this release.
>
> Please do use the new runtime/metrics package!
>
> Most of the other metrics should be there in some form (e.g. the divisions
> are a little different; they're meant to be more orthogonal to each
> other... GC pause latencies are now in a histogram) and new ones are going
> to be added in the next release and in the future. Also: today, it does not
> have the same stop-the-world penalty that ReadMemStats has, so I recommend
> it on that basis.
>
> On Tue, Apr 20, 2021 at 3:08 PM Ian Lance Taylor  wrote:
>
>> [ + mknyszek ]
>>
>> On Tue, Apr 20, 2021 at 11:12 AM Marco A.  wrote:
>> >
>> > Hi everyone,
>> >
>> > I was considering using the new stable metrics interface with go 1.16 (
>> https://golang.org/pkg/runtime/metrics/) for our program and I was also
>> wondering why things like TotalAlloc (
>> https://golang.org/pkg/runtime/#MemStats) had been dropped in the
>> available metrics.
>> >
>> > Any particular reasoning behind 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.
>> > To view this discussion on the web visit
>> https://groups.google.com/d/msgid/golang-nuts/c12d3534-d0b3-4567-9bc8-7cdcfb63c23cn%40googlegroups.com
>> .
>>
>

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


Re: [go-nuts] TotalAlloc dropped in runtime/metrics

2021-04-20 Thread 'Michael Knyszek' via golang-nuts
Oh gosh, I think TotalAlloc, Mallocs, and Frees are actually an oversight
on my part. Sorry about that. They're very easy to add and I can probably
even add them for this release.

Please do use the new runtime/metrics package!

Most of the other metrics should be there in some form (e.g. the divisions
are a little different; they're meant to be more orthogonal to each
other... GC pause latencies are now in a histogram) and new ones are going
to be added in the next release and in the future. Also: today, it does not
have the same stop-the-world penalty that ReadMemStats has, so I recommend
it on that basis.

On Tue, Apr 20, 2021 at 3:08 PM Ian Lance Taylor  wrote:

> [ + mknyszek ]
>
> On Tue, Apr 20, 2021 at 11:12 AM Marco A.  wrote:
> >
> > Hi everyone,
> >
> > I was considering using the new stable metrics interface with go 1.16 (
> https://golang.org/pkg/runtime/metrics/) for our program and I was also
> wondering why things like TotalAlloc (
> https://golang.org/pkg/runtime/#MemStats) had been dropped in the
> available metrics.
> >
> > Any particular reasoning behind 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.
> > To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/c12d3534-d0b3-4567-9bc8-7cdcfb63c23cn%40googlegroups.com
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAFza%2Bu954NiVW63%3DwGQD-97jXdats6UAB9p%2BrpiZHrLYP4EbRA%40mail.gmail.com.


Re: [go-nuts] Why does Go ignore HTTP_PROXY and HTTPS_PROXY if the proxy address is localhost

2021-04-14 Thread Michael Baker

On 14/04/2021 20:25, Jeff Peck wrote:


Just a complete shot in the dark. Have you verified that the 
environment variables you set are indeed getting picked up inside of 
your application? Try checking the output of os.GetEnv("HTTP_PROXY"), 
os.GetEnv("HTTPS_PROXY"), and os.GetEnv("NO_PROXY"). Make sure that if 
NO_PROXY is set that it isn't overriding your local proxy.



You could also try setting the lowercase versions of these env vars:

https://github.com/golang/net/blob/master/http/httpproxy/proxy.go

func FromEnvironment() *Config {
    return {
        HTTPProxy:  getEnvAny("HTTP_PROXY", "http_proxy"),
        HTTPSProxy: getEnvAny("HTTPS_PROXY", "https_proxy"),
        NoProxy:    getEnvAny("NO_PROXY", "no_proxy"),
        CGI:    os.Getenv("REQUEST_METHOD") != "",
    }
}

Thanks for the ideas Jeff. I already found out what the issue was though 
- see my other reply.






--
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/3b6c84a4-fed3-0bed-3c17-b595a3239066%40gmail.com.


Re: [go-nuts] Modules... why it has to be so painfull?

2021-04-09 Thread Michael Ellis
FWIW, I completely agree with the sentiment that confusing documentation 
has created pain and unnecessary difficulty for solo developers.  I try to 
keep in mind that Go was developed for use by large teams working on 
million line programs and that I'm lucky to be able to piggyback on the 
efforts of top-notch talent. 

That being said, here is a recipe that seems to work -- for my purposes at 
least.  It's really just a restatement of what others have said in this and 
related threads:

1. Create a directory that will hold your local projects.  I think it best 
not to use ~/go/src.  My directory is ~/localgo,  I'll use that name in in 
what follows, though there's nothing special about it.
2. Undefine GOPATH, e.g. unset GOPATH
3.  Initialize a module named for the directory, i.e. cd ~/localgo; go mod 
init localgo
4. Move your package and cmd project underneath ~/localgo. 
5. When importing local package named "somepkg" use import localgo/somepkg
6. If a package in your local directory is something you've published, you 
have three choices when importing it:

   - Import it from your published repository,
   - Import from your published repository and use "replace" to force the 
   import to use the localgo copy,
   - Import directly from localgo (as in item 5).

To make this a little more concrete here's a portion of my localgo tree 
with two packages and two command projects.  Notice that mypkg and myprog 
do not have go.mod files yet myprog is able to import mypkg and build 
without error.  Package tbchrom, on the other hand, is already (privately) 
published and versioned on GitHub.  It's still under development. Having it 
cloned under localgo allows me to reference it from command tbflash which 
is not yet published.  I'm using the replace statement in tbflash's go.mod 
file, i.e.,  replace github.com/Michael-F-Ellis/tbchrom v1.0.0 => 
/Users/mellis/localgo/tbchrom

localgo
├── go.mod
├── mypkg
│   └── pkg.go
├── myprog
│   └── main.go
├── tbchrom
│   ├── .git
│   ├── .gitignore
│   ├── .vscode
│   ├── go.mod
│   ├── go.sum
│   ├── parser.go
│   ├── parser_test.go
│   ├── rhythm.go
│   ├── rhythm_test.go
│   ├── smf.go
│   └── smf_test.go
└── tbflash
├── go.mod
├── go.sum
├── main.go
├── main_test.go
└── tbflash.json

I like this solution because it's consistent and flexible. It's consistent 
in that all the go toolchain commands,  vet, build, ... etc., work the same 
regardless of whether a package or command if version controlled or has a 
go.mod file.  It's flexible, in large part, because it's consistent. I can 
start a project with bare Go code and add module support and version 
control as needed.

Hope someone finds it useful.  If you know of any awful pitfalls, please 
let me know.

On Friday, April 9, 2021 at 5:34:37 PM UTC-4 ohir wrote:

> Dnia 2021-04-07, o godz. 14:31:07
> Slawomir Pryczek  napisał(a):
>
> > Anyone has an idea for a reasonable solution which will allow easy 
> > refactoring and code organization in packages, in this new model?
>
> Idea is here: https://github.com/golang/go/issues/44347
>
> Whether is it reasonable or not — objectively — I can not tell as I am an 
> author.
> Though I'd like to see other's opinion whether proposed solution would 
> work for them.
>
> TC.
>
> -- 
> Wojciech S. Czarnecki
> << ^oo^ >> OHIR-RIPE
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/34e47688-3644-4005-a226-262fc2c480bfn%40googlegroups.com.


Re: [go-nuts] Re: [golang-dev] Go 1.16.3 and Go 1.15.11 are released

2021-04-02 Thread 'Michael Pratt' via golang-nuts
mgcsweepbuf.go was deleted in 1.16, so it seems you still have files from
1.15 sitting around in /usr/local/go/.

On Fri, Apr 2, 2021 at 4:13 AM Jan Mercl <0xj...@gmail.com> wrote:

> On Thu, Apr 1, 2021 at 11:52 PM Dmitri Shuralyov 
> wrote:
>
> > We have just released Go versions 1.16.3 and 1.15.11, minor point
> releases.
>
> Cleared everything ($ go clean -cache -modcache -testcache ; rm -rf ~/pkg
> ~/.cache/go-build) and upgraded from 1.15.10 to 1.16.3. Now I am seeing
> while hacking some current project:
>
> jnml@3900x:~/src/modernc.org/qbe$ go test
> # runtime
> /usr/local/go/src/runtime/mgcsweepbuf.go:87:80: memstats.gc_sys undefined
> (type mstats has no field or method gc_sys)
> /usr/local/go/src/runtime/mgcsweepbuf.go:106:102: memstats.gc_sys
> undefined (type mstats has no field or method gc_sys)
> FAIL modernc.org/qbe [build failed]
> jnml@3900x:~/src/modernc.org/qbe$ go version
> go version go1.16.3 linux/amd64
> jnml@3900x:~/src/modernc.org/qbe$ go env
> GO111MODULE=""
> GOARCH="amd64"
> GOBIN=""
> GOCACHE="/home/jnml/.cache/go-build"
> GOENV="/home/jnml/.config/go/env"
> GOEXE=""
> GOFLAGS=""
> GOHOSTARCH="amd64"
> GOHOSTOS="linux"
> GOINSECURE=""
> GOMODCACHE="/home/jnml/pkg/mod"
> GONOPROXY=""
> GONOSUMDB=""
> GOOS="linux"
> GOPATH="/home/jnml"
> GOPRIVATE=""
> GOPROXY="https://proxy.golang.org,direct;
> GOROOT="/usr/local/go"
> GOSUMDB="sum.golang.org"
> GOTMPDIR=""
> GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
> GOVCS=""
> GOVERSION="go1.16.3"
> GCCGO="gccgo"
> AR="ar"
> CC="gcc"
> CXX="g++"
> CGO_ENABLED="1"
> GOMOD="/home/jnml/src/modernc.org/qbe/go.mod"
> CGO_CFLAGS="-g -O2"
> CGO_CPPFLAGS=""
> CGO_CXXFLAGS="-g -O2"
> CGO_FFLAGS="-g -O2"
> CGO_LDFLAGS="-g -O2"
> PKG_CONFIG="pkg-config"
> GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0
> -fdebug-prefix-map=/tmp/go-build1728759906=/tmp/go-build
> -gno-record-gcc-switches"
> jnml@3900x:~/src/modernc.org/qbe$
>
> Any ideas what's wrong? 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.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/CAA40n-XUw%3D_SBa-dTVNFVuKKWdDreBjScwMxpHk4DGR7MyK-YQ%40mail.gmail.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CALoThU86odpTdo8oFatbpyc%3Dc-o%3Di6%3DHToxrDuTF03zEeafm_A%40mail.gmail.com.


Re: [go-nuts] string matching

2021-04-01 Thread Michael Poole
You were on a good start with strings.Index().  The key is to move
past the pattern you searched for, assuming it was found.

Something like this should work, if `bigString` is what you are
searching over, and depending on whether "Core Count:" might be on the
first line or not:

pattern := "\nCore Count: "
if start := strings.Index(bigString, pattern); start >= 0 {
var nCores int
_, err := fmt.Sscanf(bigString[start+len(pattern):], "%d", )
if err == nil {
fmt.Println("Number of cores:", nCores)
}
}

As you can see, the regular expression-based solution suggested by
others leads to less code.  This input string is so short that CPU
usage will be negligible for most purposes, outweighed by graceful
error handling and code maintenance concerns.

Best regards,
Michael


On Thu, Apr 1, 2021 at 2:28 PM Sharan Guhan  wrote:
>
> Hi Experts,
>
> New to Golang and finding it non trivial to achieve the below efficiently :-) 
> Any pointers will help..
>
> I have a huge string as below  .. Now from this I want to extract the number 
> "18" after "Core count".. I was thinking of walking through each string with 
> Spilt("\n"), but that will make it slower. I also tried strings.Index with 
> "Core count", but unable to see how to pull the 18 from this..
>
> Sharan
>
>
> "Version: Intel(R) Xeon(R) Gold 6140 CPU @ 2.30GHz
> Voltage: 1.6 V
> External Clock: 100 MHz
> Max Speed: 4000 MHz
> Current Speed: 2300 MHz
> Status: Populated, Enabled
> Upgrade: Socket LGA3647-1
> L1 Cache Handle: 0x004D
> L2 Cache Handle: 0x004E
> L3 Cache Handle: 0x004F
> Serial Number: Not Specified
> Asset Tag: UNKNOWN
> Part Number: Not Specified
> Core Count: 18"
>
> --
> 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/CAGOT8aq8btVfAYWCpGz69cvPG_OQomNGyUjBg7oa85%2BAKqp7yQ%40mail.gmail.com.

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


Re: [go-nuts] Finding error type for `errors.As` and `errors.Is`

2021-04-01 Thread 'Michael Schaller' via golang-nuts
Roger, I think you slightly misunderstood me. ;-)

It is true that `As` and `Is` methods can be used to allow `errors.As` and 
`errors.Is` to handle error types that aren't actually in the error chain.

However my question was if an `errors.Chain` function which returns details 
about the error types and values in the error chain would be a worthwhile 
addition to Go's `errors` package.

On Wednesday, March 31, 2021 at 7:33:32 PM UTC+2 rog wrote:

> On Wed, 31 Mar 2021 at 18:05, 'Michael Schaller' via golang-nuts <
> golan...@googlegroups.com> wrote:
>
>> Hi everyone,
>>
>> I often encounter deep error chains where errors are wrapped across 
>> several Go packages and that makes it often hard to find a usable error 
>> type to use with `errors.As` or `errors.Is`.
>>
>> Could it make sense to add an `errors.Chain` function to Go that returns 
>> a slice with tuples of error type (reflect.Type) and the respective error?
>>
>
> Unfortunately that's not possible in general because errors in the change 
> can implement their own `As` and `Is` methods, so an error can appear
> to have some type T in the chain (i.e. errors.As(new(T)) returns true) 
> without *actually *having that type in the chain.
>
> For example: https://play.golang.org/p/-IAKMrD8FlG
>
> It's a shame in my view, but that's what we've got.
>
>   cheers,
> rog.
>
>
>> Quick example:
>> https://play.golang.org/p/hDW0_6P7O2Y
>>
>> Best,
>>
>> Michael
>>
>> -- 
>> 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.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/golang-nuts/acab291d-21bc-4c84-a19a-7f9901cc8035n%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/acab291d-21bc-4c84-a19a-7f9901cc8035n%40googlegroups.com?utm_medium=email_source=footer>
>> .
>>
>

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


[go-nuts] golang/mobile: Could we add GitHub Actions for PRs?

2021-03-22 Thread Michael Chong
GitHub Actions  has been introduced 
for a while.

For PRs of go-mobile , only *google-cla 
*is running on GitHub Actions.
I wonder whether we can add support like automatic testing?


-- 
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/e6194e76-bd34-40d0-995e-dff5110b98afn%40googlegroups.com.


[go-nuts] Re: encoding/html package to generate html markup programmatically

2021-03-15 Thread Michael Ellis
goht <https://github.com/Michael-F-Ellis/goht> might be what you're looking 
for.

On Sunday, March 14, 2021 at 7:36:52 PM UTC-4 atd...@gmail.com wrote:

> Hi,
>
> I am currently thinking about implementing SSR for a Go client-side 
> framework.
> Not only that but I would like to be able to create static html from the 
> same code I use to create dynamic  wasm-based webapps.
>
> I was trying to find a package that would enable me to generate an html 
> document but seems like none exists.
>
> Do you think it is possible to use encoding/xml to create an xhtml 
> document?
>
>
> That would allow me to create something like MarkupPy that would replace 
> js DOM created element by html element.
>
>

-- 
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/33063788-a96e-40f3-820a-78a34b7725f1n%40googlegroups.com.


Re: [go-nuts] Modules and internal packages

2021-03-04 Thread Michael Ellis
Just to close the loop, I've got a solution that's working well enough for 
my personal use.  

It takes advantage of GitHub's Template repo feature and the gh CLI tool to 
simplify the process of creating a new repository with a clone of the 
skeleton and a local copy thereof.  Using Axel's suggestion (thx!), I added 
an Init section to the magefile to walk the project tree changing any 
import references to match the new repo before building the app for the 
first time.

Thanks again for the help and explanations.
On Thursday, March 4, 2021 at 11:46:49 AM UTC-5 Michael Ellis wrote:

> On Thursday, March 4, 2021 at 11:01:06 AM UTC-5 axel.wa...@googlemail.com 
> wrote:
>
>> On Thu, Mar 4, 2021 at 4:51 PM Michael Ellis  
>> wrote:
>>
>>> My bad. I should have tested before writing that.  Thanks for checking.  
>>> Good to know the tools are enforcing the distinction.  Still, the import 
>>> path requirement does get in the way of being able to create a new 
>>> application by cloning and revising an existing one without doing a 
>>> recursive sed (or equivalent thereof).
>>>
>>
>> I agree :) And as I said, we could probably make relative imports work. 
>> But currently, the mapping from import paths to packages in a single go 
>> binary is 1-1. If we would allow you to use relative imports *as well,* 
>> that would be lost. Or we would have to force you to do one *or* the 
>> other per module. Either way, it seems like a non-trivial and potentially 
>> confusing transition. At which point we get back to "your usecase seems 
>> fairly special". Not "using internal packages", but the entire "cloning an 
>> existing project/skeleton and expect to have that just work as the 
>> jumping-off point for a new one". Note that *some* search/replace like 
>> stuff is still going to be needed anyway - at the very least, `go.mod` 
>> needs to contain a user-chosen module path.
>>
>> That's why I really don't think it's worth changing. Overall, your 
>> use-case seems much better addressed by writing a tool that generates your 
>> skeleton, replacing paths as needed, instead of expecting `git clone` to 
>> serve that purpose.
>>
>  
> Ok. Thanks for coherent explanation of why it may be hard to support 
> relative imports.  The skeleton code already has a fair amount of code 
> generation at build time, so it's not unreasonable to add an "Init" target 
> to the magefile that modifies go.mod.  I'll look into ways (build tags?) to 
> avoid using internal if possible.
>
> I disagree that cloning and modifying existing projects is special.  Good 
> lord! I (along with about a million other engineers) have been doing that 
> for decades:-) My clients really don't want and shouldn't have to pay me to 
> start from scratch every time.
>
>

-- 
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/f29b9eaa-a8cc-49aa-9291-db77e81c06b0n%40googlegroups.com.


Re: [go-nuts] Modules and internal packages

2021-03-04 Thread Michael Ellis


On Thursday, March 4, 2021 at 11:01:06 AM UTC-5 axel.wa...@googlemail.com 
wrote:

> On Thu, Mar 4, 2021 at 4:51 PM Michael Ellis  wrote:
>
>> My bad. I should have tested before writing that.  Thanks for checking.  
>> Good to know the tools are enforcing the distinction.  Still, the import 
>> path requirement does get in the way of being able to create a new 
>> application by cloning and revising an existing one without doing a 
>> recursive sed (or equivalent thereof).
>>
>
> I agree :) And as I said, we could probably make relative imports work. 
> But currently, the mapping from import paths to packages in a single go 
> binary is 1-1. If we would allow you to use relative imports *as well,* 
> that would be lost. Or we would have to force you to do one *or* the 
> other per module. Either way, it seems like a non-trivial and potentially 
> confusing transition. At which point we get back to "your usecase seems 
> fairly special". Not "using internal packages", but the entire "cloning an 
> existing project/skeleton and expect to have that just work as the 
> jumping-off point for a new one". Note that *some* search/replace like 
> stuff is still going to be needed anyway - at the very least, `go.mod` 
> needs to contain a user-chosen module path.
>
> That's why I really don't think it's worth changing. Overall, your 
> use-case seems much better addressed by writing a tool that generates your 
> skeleton, replacing paths as needed, instead of expecting `git clone` to 
> serve that purpose.
>
 
Ok. Thanks for coherent explanation of why it may be hard to support 
relative imports.  The skeleton code already has a fair amount of code 
generation at build time, so it's not unreasonable to add an "Init" target 
to the magefile that modifies go.mod.  I'll look into ways (build tags?) to 
avoid using internal if possible.

I disagree that cloning and modifying existing projects is special.  Good 
lord! I (along with about a million other engineers) have been doing that 
for decades:-) My clients really don't want and shouldn't have to pay me to 
start from scratch every time.

-- 
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/8f73006c-f3b2-42ee-a754-29d13bc5fa89n%40googlegroups.com.


Re: [go-nuts] Modules and internal packages

2021-03-04 Thread Michael Ellis


On Thursday, March 4, 2021 at 10:06:01 AM UTC-5 Bryan C. Mills wrote:

>
> I would argue that the “hack” in this case is the approach of defining the 
> API in terms of copying in an entire tree of packages, rather than having 
> users of the API make function calls into a specific set of (unmodified, 
> un-relocated) packages with stable import paths.
>
> If the API is defined in terms or reflection over a set of types, why 
> substitute a package rather than (say) having the caller pass in a set of 
> instances of `reflect.Type` or similar?
>

I'm not trying to create an API.  My initial goal is to provide a working 
skeleton app for my own use that incorporates:

   - a server,
   - a wasm client,
   - a web page that loads the client,
   - a common struct that represents information to be displayed in the 
   page, changed by controls therein, and propagated back to the server 
   through the wasm client.
   - magefiles and templates that generate code in the server, client and 
   web page such that changes in the common struct are updated in all of the 
   above at build time.

The above functionality is working pretty well. I can modify, add or 
subtract members in the common struct, rebuild and run it with no other 
manual changes.  I posted here because of the problems I've encountered 
with Go modules when trying to create new app from a clone of the skeleton.

If I can make the skeleton broadly useful and make it play nice with Go 
modules,  I'll happily share it.  

 

-- 
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/d83c42f9-0892-49f4-b41c-fdd05e216eb1n%40googlegroups.com.


Re: [go-nuts] Modules and internal packages

2021-03-04 Thread Michael Ellis


On Thursday, March 4, 2021 at 10:14:03 AM UTC-5 axel.wa...@googlemail.com 
wrote:

> On Thu, Mar 4, 2021 at 3:54 PM Michael Ellis  wrote:
>
>> Not sure if my case is all that special.  Seems like the requirement for 
>> a full path to an internal package breaks the concept of "internal" because 
>> it gives everyone import access to whatever the internal package exports.
>>
>
> Really? I can't reproduce that. If I create a minimal module importing "
> github.com/Merovius/srvfb/internal/fb" and try to build that, I get an 
> error message:
>
>  foo.go:3:8: use of internal package github.com/Merovius/srvfb/internal/fb 
> not allowed
>
> So, the internal mechanism seems to work just fine, to me? Note that 
> "every importer needs to mention the full path" is not the same as 
> "everyone mentioning the full path can import".
>

My bad. I should have tested before writing that.  Thanks for checking.  
Good to know the tools are enforcing the distinction.  Still, the import 
path requirement does get in the way of being able to create a new 
application by cloning and revising an existing one without doing a 
recursive sed (or equivalent thereof).

-- 
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/35e46b0e-a730-4b27-9ca0-313ddfccf855n%40googlegroups.com.


Re: [go-nuts] Modules and internal packages

2021-03-04 Thread Michael Ellis


On Thursday, March 4, 2021 at 2:24:11 AM UTC-5 axel.wa...@googlemail.com 
wrote:

> On Thu, Mar 4, 2021 at 12:55 AM Michael Ellis  
> wrote:
>
>> Thanks even though it's not the answer I was hoping for.  Seems to me 
>> that since the Go Authors have accorded special status to directories named 
>> "internal"  the module mechanism should recognize references to it and not 
>> require a globally unique path string.  
>>
>  

>  
>>
> Maybe. There seem to be few downsides. Then again, your case is also 
> fairly special.
>

Not sure if my case is all that special.  Seems like the requirement for a 
full path to an internal package breaks the concept of "internal" because 
it gives everyone import access to whatever the internal package exports.  
It would be good to have Russ and/or Ian weigh in on this.  My feeling at 
this point is that either "internal" should be deprecated or the module 
mechanism needs to honor it.
 

>
> On Thu, Mar 4, 2021 at 3:34 AM 'Bryan C. Mills' via golang-nuts <
> golan...@googlegroups.com> wrote:
>
>> You should be able to use a `replace` directive to replace the full path "
>> github.com/Michael-F-Ellis/skeleton/internal/common" or similar.
>
>
> Using replace would still mean that a module doesn't work, when used as a 
> library. Generally, I feel that `replace` is being used for more and more 
> things it wasn't designed for, leading to more and more friction and 
> problems. I don't think we should encourage more off-label uses. 
>

Agree. Replace in this instance feels like a hack. Don't get me wrong, I 
like the concept behind go.mod and think it's generally a strong and useful 
design. That being said, I also agree with the sentiment expressed in a 
couple of other recent thread that the present implementation imposes a 
burden on coders who want to quickly sketch and test ideas in a local 
directory.  It ought to be possible to progress at least a little way 
beyond Hello World before needing an external repo.


-- 
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/c7f87f45-b944-4f00-a6a6-ad3a8d1c5d4bn%40googlegroups.com.


Re: [go-nuts] Modules and internal packages

2021-03-03 Thread Michael Ellis


On Wednesday, March 3, 2021 at 6:11:38 PM UTC-5 axel.wa...@googlemail.com 
wrote:

> On Thu, Mar 4, 2021 at 12:02 AM Michael Ellis  
> wrote:
>
>> What's the right way to handle this use case?
>>
>
> I think the right way to handle it is to modify the file. In the final 
> code, the import path should unambiguously point to where the code can be 
> found - regardless of whether it was using your skeleton to get started. 
> You might write a tool to do that modification automatically, if you want 
> to simplify things.
>

Thanks even though it's not the answer I was hoping for.  Seems to me that 
since the Go Authors have accorded special status to directories named 
"internal"  the module mechanism should recognize references to it and not 
require a globally unique path 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/63067d97-1aa3-4efb-92af-7ea0f831a873n%40googlegroups.com.


[go-nuts] Modules and internal packages

2021-03-03 Thread Michael Ellis

I recently coded up a skeleton app to use as a starting point for projects 
that include a server component and a wasm (WebAssembly) client that does 
local work in a user's browser while communicating with the server.  

The skeleton is hosted  on Github (in a private repo until I think it's 
ready to publish).  

Today I decided to clone it and start an actual project.  I've run into a 
problem with internal package imports.  

Briefly,  the skeleton has multiple source files  that import from internal 
packages, e.g.

import  "github.com/Michael-F-Ellis/skeleton/internal/common"

The purpose of the internal/common package is to define structs that need 
to be known by both the server and the wasm component.  As such, the 
package will be different in each application built from the skeleton and, 
hence, the import statements all need to be modified to reference the new 
project's module name, e.g.,

import  "gitlab.com/SomeOneElse/someproject/internal/common"

Is there now no way to simply refer to "internal/common" in the import 
statement and have the toolchain treat it as a local import.  I've tried 
using the various argument to a replace directive in go.mod with no luck so 
far.

What's the right way to handle this use case?



-- 
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/669b426e-5d0a-43a4-b086-e9e0c7213a9en%40googlegroups.com.


[go-nuts] Added polish translation of Tour of Go

2021-03-03 Thread Michael
Hi!

I've been recently working on a translation of "A Tour of Go" to Polish
language and wanted to let you know that I have a PR ready!

Kind regards
Michal Stokluska

-- 
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/CAB8%3DeVG6cyB4F67AmBFK1g-fpEhLH_T9ZJ6q6TsF22e_uzw1VQ%40mail.gmail.com.


Re: [go-nuts] Error handling

2021-02-25 Thread Michael MacInnis

>
> I realize that this thread ended up diverging into a wider discussion of 
> exceptions and error handling in general but I wanted mention one of the 
> problems I discovered and maybe a potential solution for others who may be 
> tempted to play around with something like this.
>
> I originally thought that one of bigger problems with (ab)using panic and 
> recover for control flow and trying to wrap this up in a package would be 
> forgetting to defer the function performing the recover. As mentioned 
> previously I think it's possible to structure things so that it is harder 
> to make this mistake and I think a linter could also be written to catch 
> these cases.
>
> But I think the bigger problem is the function that panics being used 
> after the function with the deferred recover exits or in a different 
> goroutine.
>
> It looks like the Go compiler's escape analysis can be used to detect this 
> though. At least currently. With an inline definition of check and a 
> deferred recover that looks like this:
>
> var check func(error)
> {
> pnc := false
>
> check = func(ce error) { // watch for "func literal escapes to 
> heap"
> if ce != nil {
> err = ce
>
> // Only panic if we haven't previously.
> if !pnc {
> pnc = true
> panic("escaping")
> }
> }
> }
>
> defer func() {
> if pnc {
> _ = recover()
> }
> }()
> }
>
> // Code that uses check.
>
> When compiled with `go build -gcflags -m` if the Go compiler says that the 
> func literal assigned to check escapes to the heap there's a good chance it 
> is being used in a way that won't end well. It even catches uses like this:
>
> c := make(chan struct{})
>
> go func() {
> check(nil)
>
> close(c)
> }()
>
> <-c
>
> where check doesn't out live the function with the deferred recover but it 
> is being used in a different goroutine. So, at least currently, it looks 
> like the compiler can be used to check for unsafe uses of a function like 
> this.
>
> What I'm wondering is are there cases that the compiler won't catch and is 
> this likely to stop working in some future release where, in a block of 
> code like the one above, the compiler will decide that the function doesn't 
> need to escape to the heap?
>
> Michael.
>

-- 
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/d99b705e-d78a-4078-8f8a-ef89a824f58cn%40googlegroups.com.


Re: [go-nuts] Error handling

2021-02-20 Thread Michael MacInnis
I don't believe anyone is talking about not handling errors. There are 
functions that perform a sequence of actions and need to go no further when 
an error is encountered. An example of this type of function is presented 
in the "Errors are Values" post:

https://blog.golang.org/errors-are-values

Another example is the CopyFile function from "Error Handling - Problem 
Overview":

https://github.com/golang/proposal/blob/master/design/go2draft-error-handling-overview.md

In these cases the caller may be better equipped to know what to do next 
when there is an error.

The "Errors are Values" post gives some examples of using the language to 
simplify error handling. The check/handle and try proposals do the same 
thing but by proposing language changes. I don't believe any of them are 
proposing not checking and/or not handling errors.

I can tell you most emphatically that I am not proposing not checking 
and/or not handling errors. I'd like to know if, for functions like the 
ones just mentioned, a pattern exists for "eliminating much of the 
boilerplate that arises if every error is checked with a rote if 
statement." And further if that pattern can be implemented as a 
library/package with acceptable trade offs.

Michael.

On Saturday, February 20, 2021 at 6:54:39 PM UTC-5 ohir wrote:

> Dnia 2021-02-20, o godz. 13:21:09
> Michael Ellis  napisał(a):
>
> > FWIW, I've put together a tiny package that, with some tradeoffs, seems 
> > useful for reducing boilerplate in the common case where a function 
> simply 
> > wants to return an error to its caller. 
>
> > The code is almost trivial. It consists of two small functions, 
> > ro.RecoverOn( err *error) and ro.ReturnOn(err error), used as follows:
>
> > in the common case where a function simply wants to return an error to 
> its caller.
>
> There is no trade off here for me (an likely many others). It is idiomatic 
> versus weird:
>
> 1. hit !er move on coding (in fact MY shortcut puts panic instead 
> of return).
>
> 2. USE: import (write) a module, setup defer stack, confuse first-time 
> reader, write a call, move on.
>
> Note that both versions on my vim take just one line off the screen 
> estate. This is true for any IDE able to fold. OK - idiomatic would take 
> two lines more if code is viewed in pager or using MS Word.
>
> > in the common case where a function simply wants to return an error to 
> its caller.
>
> It is NOT a "common" case.
>
> In the "boring" production code we are expected that any service exposed 
> to the end-user will never refuse to work, our code must try really hard to 
> complete, retrying at other server here, then at other city's or continent 
> server room until its real task can be successfully done. Resources (eg. 
> network services) needs to be acquired, then vetted, then operated on, then 
> finally released in a consistent state. 
>
> So we don't throw "something went wrong" (ie. unhandled exception) up. Nor 
> we do "Return if any error". We do check errors, then
> retry in loops. Go explicit, IN PLACE handling helps with that alot.
>
> TC,
>
> -- 
> Wojciech S. Czarnecki
> << ^oo^ >> OHIR-RIPE
>

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


Re: [go-nuts] Error handling

2021-02-20 Thread Michael MacInnis
Neat. What you and I are doing is very similar. Particularly how the 
handler is "bound" to the error and checks to make sure that the error is 
non-nil before attempting to recover.

The differences I see in our approaches are as follows:


I support wrapping an error or performing some arbitrary action. This 
wouldn't be difficult for you to add - just add a func() parameter to 
RecoverOn that is invoked when *err != nil. If you did that then we would 
both support performing actions whether an early return was triggered by 
check/ro.ReturnOn or a regular return with err set (assuming named return 
values).


I bind the check function (what you call ro.ReturnOn) to the error so that 
it can set that when passed a non-nil error. This allows check to be used 
directly, for example, on a function that only returns an error:

check(functionThatReturnsAnError())

Instead of having to do:

err = functionThatReturnsAnError()
ro.ReturnOn(err)

Binding the check and done functions means returning them both from a call 
to handle.Error. This adds one more line of code (defer done()) but means 
that check doesn't exist without this step and given that Go complains 
about unused variables it takes some work to forget to do something with 
done. My hope is that this significantly reduces the risk of an unhandled 
panic. (It's still possible to just call done and forget to defer it or 
name done _ so that the compiler won't complain, etc., etc.) As an added 
bonus people can call this pair of functions whatever they want 
(check/done, try/handle, ReturnOn/RecoverOn...). When I first posted I 
thought it would be neat to do:

check, handle := handle.Error // ...
so that the shadowing would make it impossible to call handle.Error again. 
But then I added Chain.

(It would be nice to get the handle.Errorf case down to one line but I 
haven't figured out a way to do that. Maybe something with how arguments to 
deferred function are evaluated but the function call itself isn't...)


In check I wrap the error in an unexported type:

type failure struct {
error
}

If this manages to slip by the idea is that it should be reported as an 
"unhandled error" plus the text of the actual error. It is the 
responsibility of done to unwrap the error and perform any actions on that. 
I'm paranoid about invoking recover, only invoke it when the error is the 
unexported failure type and even then check to make sure that the recovered 
value matches the error value. It is possible to always recover and then if 
we recover something we weren't supposed to, re-panic, but then we lose all 
the context for the original panic.


Looking back at the error handling problem outline I realized that I did 
not have the ability to add additional error handling actions. I added 
Chain a few days after my original post.


Michael.

On Saturday, February 20, 2021 at 4:21:10 PM UTC-5 michael...@gmail.com 
wrote:

> FWIW,  I've put together a tiny package that, with some tradeoffs, seems 
> useful for reducing boilerplate in the common case where a function simply 
> wants to return an error to its caller.  
>
> https://github.com/Michael-F-Ellis/ro
>
> The code is almost trivial. It consists of two small functions, 
> ro.RecoverOn( err *error) and ro.ReturnOn(err error), used as follows:
>
> import "github.com/Michael-F-Ellis/ro" 
>
> func myfunc() (err error) { 
> defer ro.RecoverOn() 
>
> err = SomeFunctionCall() 
> ro.ReturnOn(err)
>
> // Do more stuff 
> // ... 
> return 
> }
>
> ReturnOn panics if err is not nil.
>
> RecoverOn recovers from the panic raised by ReturnOn and the function 
> exits with whatever error value would have been returned 
> normally. RecoverOn does not interfere with panics arising outside 
> of ReturnOn.
>
> Benefits and tradeoffs (coding discipline, debugging, performance) are 
> discussed in the README.
>
> Feedback welcomed either in this thread or in the repo issues.
>

-- 
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/87c73aa0-2ea2-4125-8cc9-3fe7972a4db9n%40googlegroups.com.


Re: [go-nuts] Error handling

2021-02-20 Thread Michael Ellis
FWIW,  I've put together a tiny package that, with some tradeoffs, seems 
useful for reducing boilerplate in the common case where a function simply 
wants to return an error to its caller.  

https://github.com/Michael-F-Ellis/ro

The code is almost trivial. It consists of two small functions, 
ro.RecoverOn( err *error) and ro.ReturnOn(err error), used as follows:

import "github.com/Michael-F-Ellis/ro" 

func myfunc() (err error) { 
defer ro.RecoverOn() 

err = SomeFunctionCall() 
ro.ReturnOn(err)

// Do more stuff 
// ... 
return 
}

ReturnOn panics if err is not nil.

RecoverOn recovers from the panic raised by ReturnOn and the function exits 
with whatever error value would have been returned normally. RecoverOn does 
not interfere with panics arising outside of ReturnOn.

Benefits and tradeoffs (coding discipline, debugging, performance) are 
discussed in the README.

Feedback welcomed either in this thread or in the repo issues.

On Saturday, February 20, 2021 at 3:31:22 PM UTC-5 matthew...@nytimes.com 
wrote:

> I'm referring to errors found in the function (i.e., by calling 
> other functions). It's the responsibility of the callers of a function to 
> handle the errors it returns, and not the function itself. How can one 
> function claim responsibility for the error handling strategy of all 
> programs using it?
>
> Yes, I suppose in some sense exceptions guarantee all errors are handled 
> somewhere. Unfortunately, what I've seen of exception handling over the 
> years is that it's often "log the stack trace and keep moving", which isn't 
> all that useful, and tends to cover up real bugs. A better approach would 
> be not to catch exceptions at all, and let them crash the program (which is 
> what Go's panic will do); this ensures the bugs are really handled by 
> removing them from the program.
>
> [And given this type of exception "handling" it's not much value to the 
> author of a single function to know that the errors will all be "handled" 
> somewhere.]
>
> Unfortunately, exception handling languages tend to put all types of 
> errors, normal and abnormal *, into the same basket. Which means you can't 
> do sensible error handling for, e.g., JSON that doesn't decode, while 
> allowing the program to crash when there's a logic bug. (For non-safety 
> critical software, a crash failure is typically the safest way to fail. 
> Safety-critical software, on the other hand, avoids exception handling like 
> the plague.)
>
> * A normal error is some behavior that can reasonably be expected, such as 
> "file not found" or "no route to host", etc. Abnormal errors are logic bugs 
> in the program.
>
> An aside:
>
> Assuming you had a cyclomatic complexity calculator that took exceptions 
> into consideration, such that exceptions passing through a function counted 
> as a branch, what kind of numbers would you get? Probably pretty awful, 
> given just about any line of code would be capable of throwing an 
> exception. But exceptions typically aren't counted, so that functions are 
> thought to be far less complex than they really are in the presence of 
> exceptions.
>
> Invisible (magic) return paths through a function go against the notion of 
> "the code does what it says on the page".
>
> On Sat, Feb 20, 2021 at 1:11 PM Robert Engels  
> wrote:
>
>> Can you clarify what you mean mean by “the code does exactly what it 
>> shows on the page”? How do you know by looking at the code, or even 
>> compiling the code, that all possible errors returned by a function are 
>> handled? That to me is biggest difficult in reading (or using) others Go 
>> code. Exceptions (well written) handle this by declaring all possible error 
>> (or categories) thrown by the method. 
>>
>> This seems a real problem with long term maintenance of Go code. 
>>
>> On Feb 20, 2021, at 1:39 PM, Matthew Holiday  
>> wrote:
>>
>> 
>> Roger beat me to it.
>>
>> But allow me to rephrase,
>>
>> "The users of Go for a long time have resisted any changes to its simple, 
>> clear method of error handling despite it being a major concern of folks 
>> who don't use Go much." *
>>
>> * I'm referring to the original survey, which was worded along the lines 
>> of "what keeps you from adopting Go?"
>> (implying that the responders are those who haven't adopted Go)
>>
>> Any type of error handling that creates invisible returns in a function 
>> is a bad idea IMNSHO (an opinion backed up by various researches into the 
>> complexity of exception handling). Speaking for myself, I'd like to retain 
>> that quality of

Re: [go-nuts] Error handling

2021-02-18 Thread Michael MacInnis
At the risk of getting caught in the crossfire, I will point out again that 
I just found it interesting how close it was possible to get to something 
like check/handle with just standard language constructs. If you'll excuse 
the cuddled checks, I think this:

func CopyFile(src, dst string) (err error) {
check, done := handle.Errorf(, "copy %s %s", src, dst);
defer done()

r, err := os.Open(src); check(err)
defer r.Close()

w, err := os.Create(dst); check(err)
defer handle.Chain(, func() {
w.Close()
os.Remove(dst)
})

_, err = io.Copy(w, r); check(err)
return w.Close()
}

looks pretty similar to this:

func CopyFile(src, dst string) error {
handle err {
return fmt.Errorf("copy %s %s: %v", src, dst, err)
}

r := check os.Open(src)
defer r.Close()

w := check os.Create(dst)
handle err {
w.Close()
os.Remove(dst) // (only if a check fails)
}

check io.Copy(w, r)
check w.Close()
return nil
}

I'll probably continue playing with this. If others would like to take a 
look the code is here:

https://github.com/michaelmacinnis/handle

I'm particularly interested in any problems I may have overlooked and 
similar packages that may exist but that I haven't stumbled across.

Thanks,

Michael.

On Thursday, February 18, 2021 at 2:27:33 PM UTC-5 ren...@ix.netcom.com 
wrote:

> Yes but without robust error information (stack trace, typed error) it is 
> very hard to write that top-level handler - at least not a robust one. Plus 
> you are relying on the proper use of defer etc up the chain. This is much 
> simpler with exceptions - to me anyway. 
>
> > On Feb 18, 2021, at 10:39 AM, Kevin Chadwick  wrote:
> > 
> > 
> >> don’t think ‘single shot, short lived processes’ are the typical Go
> >> paradigm - they are usually larger , multi layer, long lived “server”
> >> processes. It’s my opinion that Gos error handling is a problem for
> >> these types. I am not saying it can’t be done but it’s harder to
> >> design/deliver/maintain.
> >> 
> > 
> > I can't agree. Long lived go server processes are made of many single 
> shot worker tasks that can send errors back just the same.
> > 
> >> Exceptions (used properly) provide a lot of information when reading
> >> the code. I don’t get the same feedback with Gos error returns. 
> > 
> > AFAICT, this is just structuring. There is nothing stopping your server 
> processes from having a documented error processor, handling returned error 
> types, possibly even from distributed services.
> > 
> > The only real difference is if the errors are tunnelled in plain sight 
> or behind the scenes. You could store rather than returning errors if you 
> wanted to. I don't think Go users should be encouraged to hide errors away.
> > 
> > -- 
> > 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.
> > To view this discussion on the web visit 
> https://groups.google.com/d/msgid/golang-nuts/65F3B450-5507-4E3C-A09B-905DCF4C0006%40gmail.com
> .
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/1c510a2c-981b-4980-8f47-7a025769e233n%40googlegroups.com.


Re: [go-nuts] Error handling

2021-02-15 Thread Michael MacInnis

>
> Go helps with that. Even team's proposal was finally retracted: 
> https://github.com/golang/go/issues/32437 Discussion there is lengthy, 
> but worth 
> reading to sense why wider community considers "boilerplate" as asset.
>

Thanks, I did follow the try proposal and the earlier check/handle proposal.

I agree that handling errors, and doing so close to where they occur, is a 
good thing. I also agree with the goals as outlined in the error handling 
problem statement. Specifically, that it would be nice if it was possible 
to make "error checks more lightweight, reducing the amount of Go program 
text dedicated to error checking". But that in doing so "error checks and 
error handling must remain explicit".

What I find interesting is how close we can get to something resembling try 
or check/handle with existing constructs.

While

f, err := os.Open(filename); check(err)
is not as terse as

f := try(os.Open(filename))

there is less much less text dedicated to error checking than with

f, err := os.Open(filename)
if err != nil {
// Handle err.
}

and passing err explicitly also means there isn't something to unwrap when 
debugging (to get to err) which I thought was an interesting objection to 
try.

Similarly, while

check, handle := handle.Errorf(, "copy %s %s", src, dst)
defer handle()

requires the enclosing function to use named return values and is not as 
terse as

handle err {
fmt.Errorf("copy %s %s: %v", src, dst, err)
}

it is close to the suggestion for decorating errors in the try proposal

defer fmt.HandleErrorf(, "copy %s %s", src, dst)

The problem is that forgetting to defer handle (in my version) means that 
check will cause an unrecovered panic. I'm also wondering if there are 
other interactions that I've overlooked. It is these more mechanism than 
policy considerations where I'm looking for feedback.

Michael.

-- 
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/f6673e29-1366-476a-8fcc-31f6a4efe22dn%40googlegroups.com.


Re: [go-nuts] What compatibility of go/ast, go/types, go/packages packages is planned, if any, when transitioning toward go2 ?

2021-02-14 Thread Michael Ellis
On Wednesday, 27 January 2021 at 23:28:17 UTC+1 Ian Lance Taylor wrote:
To be clear, there is no Go 2, and there are no plans for Go 2.

Speaking as one who suffered through the ill-conceived and interminable 
Python3 transition, this is the best news I've heard since discovering and 
falling in love (well, it *is* Valentines Day) with Go a couple of years 
ago.  Thank you!

On Thursday, January 28, 2021 at 2:26:37 PM UTC-5 Ian Lance Taylor wrote:

> On Thu, Jan 28, 2021 at 3:43 AM 'Carla Pfaff' via golang-nuts
>  wrote:
> >
> > On Wednesday, 27 January 2021 at 23:28:17 UTC+1 Ian Lance Taylor wrote:
> >>
> >> To be clear, there is no Go 2, and there are no plans for Go 2.
> >
> >
> > For someone who follows the mailing lists and issue comments this has 
> been known for a while, but it's easy to see where the confusion comes 
> from, given these blog posts:
> >
> > https://blog.golang.org/toward-go2
> > https://blog.golang.org/go2-here-we-come
> > https://blog.golang.org/go2-next-steps
> >
> > They mention backward-compatibility, but only for the initial proposals 
> "to get the ball rolling". There hasn't been a blog post titled "There are 
> no plans for Go 2" or "Go 2 is not what you think it is" so far. The 
> current policy seems to be this document:
> >
> > "Proposal: Go 2 transition": 
> https://go.googlesource.com/proposal/+/refs/heads/master/design/28221-go2-transitions.md
> > "If the above process works as planned, then in an important sense there 
> never will be a Go 2."
> >
> > It is labeled "Proposal", but it doesn't seem to be a proposal in the 
> usual proposal process sense, and many may have missed it.
>
> You're right, I wrote that poorly. People use "Go 2" in various
> different ways. I should have said: there is no plan to ever break
> backward compatibility with earlier versions of Go.
>
> Ian
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/77ade682-6cb2-45ee-b7bd-7447d3b41a7dn%40googlegroups.com.


Re: [go-nuts] Re: How to get VSCode to use different Go env vars for different directories in the same repo?

2021-02-14 Thread Michael Ellis
I've opened https://github.com/golang/vscode-go/issues/1225.

-- 
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/CAK6kDbZXw1HRs5tqX50LFfv%3Dg_drosjMXbN13_ELD5pYCyt8bQ%40mail.gmail.com.


Re: [go-nuts] Re: How to get VSCode to use different Go env vars for different directories in the same repo?

2021-02-14 Thread Michael Ellis
>
> As vscode-go is now curated by the Go team [
> https://blog.golang.org/vscode-go]
> I think you should raise issue at https://github.com/golang/vscode-go.
> Your project layout (original one) seems good and straightforward, and the
> need
> for having per-folder environment settings or build-tags is real.
> It shouldn't be the IDE that dictates Go project structure, IMO.
>

I agree about wanting project structure independent of IDE.  I'm not so
sure if this is something vscode-go can reasonably be expected to solve,
though.

If I'm understanding correctly,  vscode-go would need to parse each file
for build-tags and pass that information to the go tool chain, presumably
as environment variables.

That sounds doable for standard tags that map to supported values for GOOS,
GOARCH, etc., but I wonder what problems would be caused by non-standard
tags, e.g. "+build mage" for magefiles.


Cheers,
Mike

*“I want you to act as if the house was on fire. Because it is.” — Greta
Thunberg*


On Sun, Feb 14, 2021 at 11:32 AM Wojciech S. Czarnecki 
wrote:

> Dnia 2021-02-14, o godz. 10:54:02
> Michael Ellis  napisał(a):
>
> > I wrote a detailed answer on StackOverflow
>
> Thank you.
>
> As vscode-go is now curated by the Go team [
> https://blog.golang.org/vscode-go]
> I think you should raise issue at https://github.com/golang/vscode-go.
> Your project layout (original one) seems good and straightforward, and the
> need
> for having per-folder environment settings or build-tags is real.
> It shouldn't be the IDE that dictates Go project structure, IMO.
>
> TC,
>
> --
> Wojciech S. Czarnecki
>  << ^oo^ >> OHIR-RIPE
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "golang-nuts" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/golang-nuts/2vI1CA76HPI/unsubscribe.
> To unsubscribe from this group and all its topics, 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/20210214173156.1a9edbfa%40xmint
> .
>

-- 
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/CAK6kDbZ8E7py6hX_8Bp7Z-gixoZg6MNeJzZy00Vr0y4zoBhyow%40mail.gmail.com.


Re: [go-nuts] Re: How to get VSCode to use different Go env vars for different directories in the same repo?

2021-02-14 Thread Michael Ellis
Thanks, Space & Alex.  I already understood the need for the Go tool
environment vars, just didn't know how to apply them on a per-folder
basis.  Thanks for outlining how to use multiple instances of VSCode.  It
doesn't appeal to my workflow preferences, but then *à chacun son goût* as *nos
amis français* would put it.

I ended up learning how to use VSCode Multi-Root Workspaces to permit a
separate settings.json in wasm/ folder.  That seems to work fairly well.  I
wrote a detailed answer on StackOverflow
<https://stackoverflow.com/questions/66188534/how-to-get-vscode-to-use-different-go-env-vars-for-different-directories-in-the>
for
anyone who's interested.

Cheers,
Mike

*“I want you to act as if the house was on fire. Because it is.” — Greta
Thunberg*


On Sun, Feb 14, 2021 at 7:11 AM Space A.  wrote:

> Hi,
>
> the solution would be:
>
> 1. Protect WASM source files with build flags so that when you open a
> "backend" main sources, IDE won't complain about "syscall/js", like this:
> // +build js,wasm
> 2. Open `wasm` directory in second instance of VS Code for which you would
> set GOOS and GOARCH for a workspace. When editing settings in json, click
> on "workspace" tab and VS Code will create .vscode/settings.json in `wasm`
> directory. Put something like:
> {
> "go.toolsEnvVars": {
> "GOOS": "js",
> "GOARCH": "wasm",
> }
> }
> in there.
> 3. In future, work in two instances of VS Code, even though if logically
> it's a different parts of same project and could be under the same Go
> module. All IDE features will work fluently. I haven't seen any problems
> with this approach so far.
>
>
> суббота, 13 февраля 2021 г. в 23:42:06 UTC+3, michael...@gmail.com:
>
>> *(Sorry for posting what is mostly a VSCode question. I've asked it on
>> StackOverflow without getting any responses.  Am reposting here in the hope
>> that some has already run into this problem and figured out how to deal
>> with it.)*
>>
>> I have a Go project that builds a WebAssembly (WASM)  app and a backend
>> server for it. Both pieces build and run without errors. VSCode, however,
>> produces an annoying linter error in the WASM app.
>>
>> ```
>> could not import syscall/js (no required module provides package
>> "syscall/js")
>> ```
>>
>> The problem, as I currently understand it, is that VSCode doesn't infer
>> from the build tags that it should invoke `gopls` with `env GOOS=js
>> GOARCH=wasm` and that one solution is to set these tags as workspace Go
>> environment vars.
>>
>> The app design, however, relies on providing a common internal package to
>> both the wasm and the server code so that each side sees some struct
>> definitions that simplify the interface between them. To that end, the repo
>> is organized (simplified view) as follows:
>>
>> ```
>> cmd
>> ├── internal
>> │   └── common
>> │   ├── common.go
>> │   └── common_test.go
>> ├── server
>> │   └── main.go
>> └── wasm
>> └── main.go
>> ```
>>
>> How can I configure VSCode to use `env GOOS=js GOARCH=wasm` when linting
>> the wasm directory and not for other directories?
>>
>>
>>
>>
>>
>> --
> You received this message because you are subscribed to a topic in the
> Google Groups "golang-nuts" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/golang-nuts/2vI1CA76HPI/unsubscribe.
> To unsubscribe from this group and all its topics, 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/ed6caf0c-64ec-454d-8926-dc9cbb98d8a5n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/ed6caf0c-64ec-454d-8926-dc9cbb98d8a5n%40googlegroups.com?utm_medium=email_source=footer>
> .
>

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


  1   2   3   4   5   6   7   8   9   >