Re: [go-nuts] Can't figure out how to create an All() iter.Seq[T] method

2024-03-13 Thread 'Mark' via golang-nuts
Thank you, that solved the problem.

On Wednesday, March 13, 2024 at 1:22:06 PM UTC Sebastien Binet wrote:

> hi Mark,
>
> On Wed Mar 13, 2024 at 13:32 CET, 'Mark' via golang-nuts wrote:
> > I've been trying to learn how to create an `All() iter.Seq[T]` method
> > for a
> > simple set type (a map wrapper):
> >
> > playground <https://go.dev/play/p/wtWvvTf33AF?v=gotip>
> >
> > It won't work in the playground of course, but when I do:
> > `GOEXPERIMENT=rangefunc go run .`
> > using Go 1.22 I get this error:
> > ```
> > cannot use func(yield func(int, T) bool) {…} (value of type func(yield
> > func(int, T) bool)) as iter.Seq[T] value in return statement
> > ```
> > Can someone help me get this right please?
>
> IIRC,
>
> ```
> return func(yield func(int, T) bool) { ... }
> ```
> is for iter.Seq2[int,T]
>
> if you want iter.Seq[T] you should write:
>
> ```
> return func (yield func(T) bool) { ... }
> ```
> (and adapt accordingly)
>
> hth,
> -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/063c64c8-ebfe-4039-abce-4b405e74d3e8n%40googlegroups.com.


[go-nuts] Can't figure out how to create an All() iter.Seq[T] method

2024-03-13 Thread 'Mark' via golang-nuts
I've been trying to learn how to create an `All() iter.Seq[T]` method for a 
simple set type (a map wrapper):

playground 

It won't work in the playground of course, but when I do:
`GOEXPERIMENT=rangefunc go run .`
using Go 1.22 I get this error:
```
cannot use func(yield func(int, T) bool) {…} (value of type func(yield 
func(int, T) bool)) as iter.Seq[T] value in return statement
```
Can someone help me get this right please?

```
package main

import (
"cmp"
"fmt"
"iter"
)

func main() {
s := New(5, 10, 15, 20, 35)
for v := range s.All() {
fmt.Println(v)
}
}

type Set[T cmp.Ordered] map[T]struct{}

func New[T cmp.Ordered](elements ...T) Set[T] {
set := make(Set[T], len(elements))
for _, element := range elements {
set[element] = struct{}{}
}
return set
}

func (me Set[T]) All() iter.Seq[T] {
return func(yield func(int, T) bool) { // ERROR
n := 0
for key := range me {
if !yield(n, key) {
return
}
n++
}
}
}
```

-- 
You received this message because you are subscribed to the Google 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/73161d74-12eb-4be0-9ea4-a35a25758e8en%40googlegroups.com.


[go-nuts] range func experiment typo?

2024-01-19 Thread 'Mark' via golang-nuts
In the RangefuncExperiment  doc it 
says:

for k, v := range g { ... } // g has type Seq[K,V], k and v have types K 
and V

but shouldn't this be:

for k, v := range g { ... } // g has type Seq2[K,V], k and v have types K 
and V

Anyway, it looks interesting.

-- 
You received this message because you are subscribed to the Google 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/d5299dee-cabc-40a9-9c93-b9fd17149045n%40googlegroups.com.


Re: [go-nuts] a simple linux audio player pkg?

2023-11-23 Thread 'Mark' via golang-nuts
I just converted the []float32 to []byte (see function below) and it works.
But the sound produced while recognizable is very staticy and I don't know 
why.

func floats32ToBytes(fs []float32) []byte {
var buf bytes.Buffer
for _, f := range fs {
if err := binary.Write(, binary.LittleEndian, f); err != nil {
panic(err)
}
}
return buf.Bytes()
}

On Thursday, November 23, 2023 at 10:03:24 AM UTC Mark wrote:

> I've now tried using those libraries, but there seems to be an 
> incompatibility []float32 vs []byte.
> Here's the error:
>
> ./play.go:24:29: cannot use reader (variable of type *oggvorbis.Reader) as 
> io.Reader value in argument to otoCtx.NewPlayer: *oggvorbis.Reader does not 
> implement io.Reader (wrong type for method Read)
> have Read([]float32) (int, error)
> want Read([]byte) (int, error)
>
> And here's the code (main.go):
>
> package main
>
> import (
> "log"
> "os"
> "time"
>
> //"github.com/ebitengine/oto/v3"
> "github.com/hajimehoshi/oto/v2"
> "github.com/jfreymuth/oggvorbis"
> )
>
> func main() {
> log.SetFlags(0)
> file, err := os.Open(os.Args[0])
> checkErr(err)
> defer file.Close()
> reader, err := oggvorbis.NewReader(file)
> checkErr(err)
> otoCtx, readyCh, err := oto.NewContext(reader.SampleRate(),
> reader.Channels(), 2)
> checkErr(err)
> <-readyCh // wait for h/w
> player := otoCtx.NewPlayer(reader)
> defer player.Close()
> player.Play()
> for player.IsPlaying() {
> time.Sleep(time.Millisecond * 10)
> }
> }
>
> func checkErr(err error) {
> if err != nil {
> log.Fatal(err)
> }
> }
>
> On Wednesday, November 22, 2023 at 10:31:25 PM UTC Raffaele Sena wrote:
>
>> I have used github.com/jfreymuth/oggvorbis to read the ogg file (and 
>> convert to PCM) and github.com/ebitengine/oto/v3 to play the PCM.
>> I don't know of a full ogg player in Go
>>
>>
>> On Wed, Nov 22, 2023 at 2:02 PM 'Mark' via golang-nuts <
>> golan...@googlegroups.com> wrote:
>>
>>> Is there a simple vorbis/oga audio player package for Go that works on 
>>> Linux.
>>> The only API I need is something like this:
>>>
>>> player.SetFilename(string) error // string is say tune.ogg; stops 
>>> playing previous if any
>>> player.Play(float32) error // plays current filename from given second 
>>> e.g. 0.0 for the beginning
>>> player.Pause() (float32, error) // pauses current playing and returns 
>>> position
>>> player.Resume() error // resumes playing
>>> player.Secs() float32 // returns current position
>>>
>>> The ones I've seen on awsome go either don't seem to play ogg format or 
>>> are far more sophisticated than I need.
>>>
>>> -- 
>>> You received this message because you are subscribed 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/a38e3a9b-a357-4c85-aa4d-a7a4322ec216n%40googlegroups.com
>>>  
>>> <https://groups.google.com/d/msgid/golang-nuts/a38e3a9b-a357-4c85-aa4d-a7a4322ec216n%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/4bbdeb78-6ac8-49c3-b71f-a270bb090a38n%40googlegroups.com.


Re: [go-nuts] a simple linux audio player pkg?

2023-11-23 Thread 'Mark' via golang-nuts
I've now tried using those libraries, but there seems to be an 
incompatibility []float32 vs []byte.
Here's the error:

./play.go:24:29: cannot use reader (variable of type *oggvorbis.Reader) as 
io.Reader value in argument to otoCtx.NewPlayer: *oggvorbis.Reader does not 
implement io.Reader (wrong type for method Read)
have Read([]float32) (int, error)
want Read([]byte) (int, error)

And here's the code (main.go):

package main

import (
"log"
"os"
"time"

//"github.com/ebitengine/oto/v3"
"github.com/hajimehoshi/oto/v2"
"github.com/jfreymuth/oggvorbis"
)

func main() {
log.SetFlags(0)
file, err := os.Open(os.Args[0])
checkErr(err)
defer file.Close()
reader, err := oggvorbis.NewReader(file)
checkErr(err)
otoCtx, readyCh, err := oto.NewContext(reader.SampleRate(),
reader.Channels(), 2)
checkErr(err)
<-readyCh // wait for h/w
player := otoCtx.NewPlayer(reader)
defer player.Close()
player.Play()
for player.IsPlaying() {
time.Sleep(time.Millisecond * 10)
}
}

func checkErr(err error) {
if err != nil {
log.Fatal(err)
}
}

On Wednesday, November 22, 2023 at 10:31:25 PM UTC Raffaele Sena wrote:

> I have used github.com/jfreymuth/oggvorbis to read the ogg file (and 
> convert to PCM) and github.com/ebitengine/oto/v3 to play the PCM.
> I don't know of a full ogg player in Go
>
>
> On Wed, Nov 22, 2023 at 2:02 PM 'Mark' via golang-nuts <
> golan...@googlegroups.com> wrote:
>
>> Is there a simple vorbis/oga audio player package for Go that works on 
>> Linux.
>> The only API I need is something like this:
>>
>> player.SetFilename(string) error // string is say tune.ogg; stops playing 
>> previous if any
>> player.Play(float32) error // plays current filename from given second 
>> e.g. 0.0 for the beginning
>> player.Pause() (float32, error) // pauses current playing and returns 
>> position
>> player.Resume() error // resumes playing
>> player.Secs() float32 // returns current position
>>
>> The ones I've seen on awsome go either don't seem to play ogg format or 
>> are far more sophisticated than I need.
>>
>> -- 
>> You received this message because you are subscribed 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/a38e3a9b-a357-4c85-aa4d-a7a4322ec216n%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/a38e3a9b-a357-4c85-aa4d-a7a4322ec216n%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/b719492d-bead-4391-8371-2a6489f9cf46n%40googlegroups.com.


Re: [go-nuts] a simple linux audio player pkg?

2023-11-23 Thread 'Mark' via golang-nuts
Thank you, I'll try them. (Well, for oto I'll try 
https://pkg.go.dev/github.com/hajimehoshi/oto/v2 since that seems to have 
more importers)

On Wednesday, November 22, 2023 at 10:31:25 PM UTC Raffaele Sena wrote:

> I have used github.com/jfreymuth/oggvorbis to read the ogg file (and 
> convert to PCM) and github.com/ebitengine/oto/v3 to play the PCM.
> I don't know of a full ogg player in Go
>
>
> On Wed, Nov 22, 2023 at 2:02 PM 'Mark' via golang-nuts <
> golan...@googlegroups.com> wrote:
>
>> Is there a simple vorbis/oga audio player package for Go that works on 
>> Linux.
>> The only API I need is something like this:
>>
>> player.SetFilename(string) error // string is say tune.ogg; stops playing 
>> previous if any
>> player.Play(float32) error // plays current filename from given second 
>> e.g. 0.0 for the beginning
>> player.Pause() (float32, error) // pauses current playing and returns 
>> position
>> player.Resume() error // resumes playing
>> player.Secs() float32 // returns current position
>>
>> The ones I've seen on awsome go either don't seem to play ogg format or 
>> are far more sophisticated than I need.
>>
>> -- 
>> You received this message because you are subscribed 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/a38e3a9b-a357-4c85-aa4d-a7a4322ec216n%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/a38e3a9b-a357-4c85-aa4d-a7a4322ec216n%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/85e7b5c4-7224-4f79-accd-ef1b4f095425n%40googlegroups.com.


[go-nuts] a simple linux audio player pkg?

2023-11-22 Thread 'Mark' via golang-nuts
Is there a simple vorbis/oga audio player package for Go that works on 
Linux.
The only API I need is something like this:

player.SetFilename(string) error // string is say tune.ogg; stops playing 
previous if any
player.Play(float32) error // plays current filename from given second e.g. 
0.0 for the beginning
player.Pause() (float32, error) // pauses current playing and returns 
position
player.Resume() error // resumes playing
player.Secs() float32 // returns current position

The ones I've seen on awsome go either don't seem to play ogg format or are 
far more sophisticated than I need.

-- 
You received this message because you are subscribed to the Google 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/a38e3a9b-a357-4c85-aa4d-a7a4322ec216n%40googlegroups.com.


[go-nuts] Re: Is there a Go equivalent to Python's ctypes library?

2023-11-21 Thread 'Mark' via golang-nuts
My reply was to Salih but somehow my reply ended up appearing first.

According to the purego docs you don't need a compiler, essentially it 
provides a means of opening a dll/so and registering and calling functions 
within the dll/so.

On Tuesday, November 21, 2023 at 12:58:20 PM UTC Tamás Gulácsi wrote:

> Which is what?
> Please share with the golang-nuts list if you've found a solution!
>
> Mark a következőt írta (2023. november 21., kedd, 11:54:11 UTC+1):
>
>> Thank you, that looks just like what I want.
>>
>> On Tuesday, November 21, 2023 at 10:21:14 AM UTC Mark wrote:
>>
>>> I would like to be able to access a dynamic C library (and ideally C++), 
>>> i.e., `.so` or `.dll` _without_ using cgo, i.e., without needing a compiler 
>>> on the target platform.
>>> Python provides a `ctypes` module with this facility. Is there an 
>>> equivalent for 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/94a176f0-a076-4140-8179-5813ef061249n%40googlegroups.com.


[go-nuts] Re: Is there a Go equivalent to Python's ctypes library?

2023-11-21 Thread 'Mark' via golang-nuts
Thank you, that looks just like what I want.

On Tuesday, November 21, 2023 at 10:21:14 AM UTC Mark wrote:

> I would like to be able to access a dynamic C library (and ideally C++), 
> i.e., `.so` or `.dll` _without_ using cgo, i.e., without needing a compiler 
> on the target platform.
> Python provides a `ctypes` module with this facility. Is there an 
> equivalent for 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/6e31d1e4-159e-4120-a76a-931df7a213f5n%40googlegroups.com.


[go-nuts] Is there a Go equivalent to Python's ctypes library?

2023-11-21 Thread 'Mark' via golang-nuts
I would like to be able to access a dynamic C library (and ideally C++), 
i.e., `.so` or `.dll` _without_ using cgo, i.e., without needing a compiler 
on the target platform.
Python provides a `ctypes` module with this facility. Is there an 
equivalent for 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/f7f9a1e1-51d2-4144-9cec-d0dcaa31411en%40googlegroups.com.


Re: [go-nuts] bufio.Scanner - possible bug or doc err?

2023-10-14 Thread 'Mark' via golang-nuts
Yes, that's a much better solution.

On Friday, October 13, 2023 at 8:40:45 PM UTC+1 Ian Lance Taylor wrote:

> On Thu, Oct 12, 2023 at 11:42 PM 'Mark' via golang-nuts
>  wrote:
> >
> > Yes, I can see now.
> >
> > Perhaps consider changing:
> >
> > Programs that need more control over error handling or large tokens, or 
> must run sequential scans on a reader, should use bufio.Reader instead.
> >
> > to:
> >
> > Programs that need more control over error handling or large tokens 
> (such as lines longer than MaxScanTokenSize), or must run sequential scans 
> on a reader, should use bufio.Reader instead.
>
> Thanks, instead of that I added a link to Scanner.Buffer
> (https://go.dev/cl/535216). I hope that will help guide people in the
> right direction.
>
> Ian
>
>
> > On Thursday, October 12, 2023 at 8:56:05 PM UTC+1 Ian Lance Taylor wrote:
> >>
> >> On Thu, Oct 12, 2023 at 10:21 AM 'Mark' via golang-nuts
> >>  wrote:
> >> >
> >> > The docs for bufio.Scanner do say
> >> > "Programs that need more control over error handling or large tokens, 
> or must run sequential scans on a reader, should use bufio.Reader instead"
> >> > Perhaps it would be more helpful to mention what the token length 
> limit is?
> >>
> >> It's MaxScanTokenSize: https://pkg.go.dev/bufio#pkg-constants . See
> >> also https://pkg.go.dev/bufio#Scanner.Buffer .
> >>
> >> 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...@googlegroups.com.
> > To view this discussion on the web visit 
> https://groups.google.com/d/msgid/golang-nuts/0392f8b3-a006-4bc0-aa54-3759aa0d3b7en%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/a74e8c1b-e11e-4f5d-b66c-43bef18e1715n%40googlegroups.com.


Re: [go-nuts] bufio.Scanner - possible bug or doc err?

2023-10-13 Thread 'Mark' via golang-nuts
Yes, I can see now.

Perhaps consider changing:

Programs that need more control over error handling or large tokens, or 
must run sequential scans on a reader, should use bufio.Reader instead. 

to:

Programs that need more control over error handling or large tokens (such 
as lines longer than MaxScanTokenSize), or must run sequential scans on a 
reader, should use bufio.Reader instead. 

Just a thought.

Thanks.
On Thursday, October 12, 2023 at 8:56:05 PM UTC+1 Ian Lance Taylor wrote:

> On Thu, Oct 12, 2023 at 10:21 AM 'Mark' via golang-nuts
>  wrote:
> >
> > The docs for bufio.Scanner do say
> > "Programs that need more control over error handling or large tokens, or 
> must run sequential scans on a reader, should use bufio.Reader instead"
> > Perhaps it would be more helpful to mention what the token length limit 
> is?
>
> It's MaxScanTokenSize: https://pkg.go.dev/bufio#pkg-constants . See
> also https://pkg.go.dev/bufio#Scanner.Buffer .
>
> 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/0392f8b3-a006-4bc0-aa54-3759aa0d3b7en%40googlegroups.com.


Re: [go-nuts] bufio.Scanner - possible bug or doc err?

2023-10-12 Thread 'Mark' via golang-nuts
I have written and attached an example that compares bufio.Reader and 
bufio.Scanner.
Here's the output from `go run .` (a line count followed by the first error 
encountered):
```
Reader 1333665 
Scanner 58 bufio.Scanner: token too long
```
This probably _won't_ fail on your 2M line file; it looks like the problem 
is with the line length of a Debian Packages file. If you have a 
Debian-derived distro you could try replacing the filename in the file with 
one from `/var/lib/apt/lists/`.

The docs for bufio.Scanner do say
"Programs that need more control over error handling or large tokens, or 
must run sequential scans on a reader, should use bufio.Reader instead"
Perhaps it would be more helpful to mention what the token length limit is?

On Thursday, October 12, 2023 at 9:45:10 AM UTC+1 Rob Pike wrote:

> I just did a simple test with a 2M line file and it worked fine, so I 
> suspect it's a bug in your code. But if not, please provide a complete 
> working executable example, with data, to help identify the problem.
>
> -rob
>
>
> On Thu, Oct 12, 2023 at 7:39 PM 'Mark' via golang-nuts <
> golan...@googlegroups.com> wrote:
>
>> I'm reading Debian *Package files, some of which are over 1M lines long.
>> I used bufio.Scanner and found that it won't read past 1M lines (I'm 
>> using Go 1.21.1 linux/amd64).
>> Is this a limitation of bufio.Scanner? If so then it ought to be in the 
>> docs.
>> Or is it a bug?
>> Or maybe I made a mistake (although using bufio.Scanner seems easy)?
>> ```
>> scanner := bufio.NewScanner(file)
>> lino := 1
>> for scanner.Scan() {
>> line := scanner.Text()
>> lino++
>> ... // etc
>> }
>> ```
>> Anyway, I've switched to using bufio.Reader and that works great.
>>
>> -- 
>> You received this message because you are subscribed 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/69f2fa03-c650-4c02-9470-51894dc56d1an%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/69f2fa03-c650-4c02-9470-51894dc56d1an%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/ebf242ab-c8aa-4de8-821b-3abe77a9da86n%40googlegroups.com.
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

const pkgFile = "/var/lib/apt/lists/gb.archive.ubuntu.com_ubuntu_" +
	"dists_jammy_universe_binary-amd64_Packages"

func main() {
	lines, err := readPackages(pkgFile)
	fmt.Println("Reader", lines, err)
	lines, err = scanPackages(pkgFile)
	fmt.Println("Scanner", lines, err)
}

func readPackages(filename string) (int, error) {
	file, err := os.Open(filename)
	if err != nil {
		return 0, err
	}
	defer file.Close()
	reader := bufio.NewReader(file)
	lines := 0
	for {
		_, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		} else if err != nil {
			return 0, err
		}
		lines++
	}
	return lines, nil
}

func scanPackages(filename string) (int, error) {
	file, err := os.Open(filename)
	if err != nil {
		return 0, err
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	lines := 0
	for scanner.Scan() {
		_ = scanner.Text()
		lines++
	}
	return lines, scanner.Err()
}


[go-nuts] bufio.Scanner - possible bug or doc err?

2023-10-12 Thread 'Mark' via golang-nuts
I'm reading Debian *Package files, some of which are over 1M lines long.
I used bufio.Scanner and found that it won't read past 1M lines (I'm using 
Go 1.21.1 linux/amd64).
Is this a limitation of bufio.Scanner? If so then it ought to be in the 
docs.
Or is it a bug?
Or maybe I made a mistake (although using bufio.Scanner seems easy)?
```
scanner := bufio.NewScanner(file)
lino := 1
for scanner.Scan() {
line := scanner.Text()
lino++
... // etc
}
```
Anyway, I've switched to using bufio.Reader and that works great.

-- 
You received this message because you are subscribed to the Google 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/69f2fa03-c650-4c02-9470-51894dc56d1an%40googlegroups.com.


[go-nuts] How to constrain an integral type's values

2023-09-08 Thread 'Mark' via golang-nuts
I often create small multi-value flag types, e.g.
```go
type mode uint8

const (
argMode mode = iota
baseMode
cmdMode
)
```
The problem is that if I write, say,  `m := baseMode`, although `m` has the 
correct type (`mode`), there is no way to constrain its values to the 
consts I've declared.
In theory I could create a `NewMode(int) mode` function and have it panic 
if the given int isn't valid; but that won't prevent, say, `m += 99`. The 
next step would be to define a full type, e.g., something like:
```go
type mode struct {
m int
}
```
This would prevent `m++` and similar since all accesses would have to go 
through the public functions. However, this would still do all its checking 
at _runtime_; whereas for this kind of use it should surely be possible to 
check at compile time.

In Pascal it is easy to declare a "subrange" type which might look like 
this in Go-like syntax:

`type mode uint8 0..2`

Is there a compile-time solution for this that I've missed?

-- 
You received this message because you are subscribed to the Google 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/8ba9ef87-984c-4b14-a760-343d2731e91dn%40googlegroups.com.


[go-nuts] Re: How to convert an svg to a png (or gif) image?

2023-08-04 Thread 'Mark' via golang-nuts
Thanks!

On Friday, August 4, 2023 at 8:46:18 AM UTC+1 Tamás Gulácsi wrote:

> https://pkg.go.dev/github.com/goki/gi/svg
>
> Mark a következőt írta (2023. augusztus 3., csütörtök, 13:18:48 UTC+2):
>
>> I know this has been asked before, just wondered if there were any 
>> pure-Go solutions?
>>
>

-- 
You received this message because you are subscribed to the Google 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/6c0c3e50-72ab-42bb-9579-f8c9c967d5f5n%40googlegroups.com.


[go-nuts] How to convert an svg to a png (or gif) image?

2023-08-03 Thread 'Mark' via golang-nuts
I know this has been asked before, just wondered if there were any pure-Go 
solutions?

-- 
You received this message because you are subscribed to the Google 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/e8a39bee-742a-4491-809a-b2230ef8ea26n%40googlegroups.com.


[go-nuts] Re: Error handling

2023-07-31 Thread 'Mark' via golang-nuts
Given that this proposal is to reduce boilerplate, and assuming the 
semantic issues could be solved, it seems to me that the 'return' is 
redundant (i.e., could be implicit) and that 'orelse' could be done with 
the existing 'else' keyword, i.e.,

```
result, err := someCall() else rest, err
```
Anyway, I really do hope the long-winded error syntax gets solved somehow!

On Monday, July 31, 2023 at 5:41:49 AM UTC+1 DrGo wrote:

> func myFirstFunction() (string, err) {
>
>result, err := myFunction() orelse return rest, err
>
> }
>
> On Sunday, July 30, 2023 at 9:27:27 PM UTC-6 Marcello H wrote:
>
>> I think the current error handling is just fine.
>> For the extra typing, they invented keyboard snippets and such.
>>
>> But for this proposal, I would like to see how a return with multiple 
>> values would look to get a better understanding.
>> ```
>> // translate this in the proposed solution?
>> func myFirstFunction() (string, err) {
>>result, err := myFunction()
>>if err != nill {
>>return rest, err
>>}
>> }
>> ```
>>
>> Op maandag 31 juli 2023 om 04:32:01 UTC+2 schreef DrGo:
>>
>>> Another possibility Jeremy is that the orelse block is executed if any 
>>> of the returned error values is not nil. 
>>>
>>> On Sunday, July 30, 2023 at 8:14:58 PM UTC-6 DrGo wrote:
>>>
 Thanks...
 yes indeed. Too many requirements but I think this solution comes close 
 to meeting them. If a rare function returns more than one error value (yet 
 to see one in the wild) then the compiler should reject orelse use and the 
 user can fallback on the (the if err!= nil) approach. 

 On Sunday, July 30, 2023 at 6:02:57 PM UTC-6 Jeremy French wrote:

> Also, errors are values, which means - although uncommon - a function 
> could return two or more error values.  Which would orelse evaluate?  
> Even 
> if you arbitrarily chose one, that would violate the explicit vs implicit 
> code flow principle.  
>
> My sympathies, OP.  I too hate the "if err!= nil" boilerplate, and 
> have suggested my own idea for fixing it, which was similarly dismantled 
> for good reasons by those more knowledgeable than me.  The truth is, this 
> problem/issue has so many restrictions placed on it (currently idiomatic 
> principles, backwards compatibility promise, explicit vs implicit, etc) 
> that the set of possible solutions is VERY narrow, possibly infinitely so.
>
> On Sunday, July 30, 2023 at 3:51:49 PM UTC-4 Brian Candler wrote:
>
> err := io.Copy(w, r) *orelse* {
> w.Close()
> os.Remove(dst)
> return fmt.Errorf("copy %s %s: %v", src, dst, err)
> }
>
> My question still stands. Semantically, what value exactly does the 
> "orelse" condition test is not equal to nil?
>
> - does it test the value from the preceding assignment? If so, is 
> "orelse" only valid immediately following an assignment expression? The 
> original posting didn't say this.  And if it *is* linked to an assignment 
> expression which assigns multiple values, does it only look at the last 
> value? (Again, that was not specified)
>
> - does it always test a variable called "err"? The original posting 
> said it was equivalent to "if err!=nil" but a later post contradicted this
>
> - does it test the value from the 'return' expression at the end of 
> the block following orelse? Except in this case, it can't because it's 
> buried inside fmt.Errorf
>
> On Sunday, 30 July 2023 at 17:55:34 UTC+1 DrGo wrote:
>
> Good point Harri,
>
> This is what the correct version will look like using this proposal 
>
> func CopyFile(src, dst string) error {
> r, err := os.Open(src) *orelse* return fmt.Errorf("copy %s %s: %v", 
> src, dst, err)
> defer r.Close()
>
> w, err := os.Create(dst); *orelse* return fmt.Errorf("copy %s %s: %v", 
> src, dst, err)
> err := io.Copy(w, r) *orelse* {
> w.Close()
> os.Remove(dst)
> return fmt.Errorf("copy %s %s: %v", src, dst, err)
> }
>
> err := w.Close() *orelse* {
> os.Remove(dst)
> return fmt.Errorf("copy %s %s: %v", src, dst, err)
> }
> }
>
> In a more complex func, the error formatting/handling code can be 
> further deduplicated by extracting it into a closure. 
> e.g., 
>
> func CopyFile(src, dst string) error {
> copyErr:= func(err error) {
> return fmt.Errorf("copy %s %s: %v", src, dst, err)
> } 
> r, err := os.Open(src) *orelse* return copyErr(err) 
> defer r.Close()
>
> w, err := os.Create(dst); *orelse* return copyErr(err)
> err := io.Copy(w, r) *orelse* {
> w.Close()
> os.Remove(dst)
> return copyErr(err)
> }
>
> err := w.Close() *orelse* {
> os.Remove(dst)
> return copyErr(err)
> }
> }
>
> On Sunday, July 30, 2023 at 8:17:31 AM UTC-6 Harri L wrote:

[go-nuts] Re: Can a struct be made comparable?

2023-07-14 Thread 'Mark' via golang-nuts
I finally worked out how to make my go-diff pkg 
<https://pkg.go.dev/github.com/mark-summerfield/go-diff> (v1.1.0) able to 
diff sequences of structs based on a key function.

On Friday, July 14, 2023 at 12:27:46 PM UTC+1 Mark wrote:

> Hi Brian,
> Ah, thank you, that helped a lot.
>
> On Friday, July 14, 2023 at 11:54:51 AM UTC+1 Brian Candler wrote:
>
>> The 'diff' package you showed identifies the changed object index by 
>> means of a "Path" attribute in the Changelog entry. If the top level object 
>> is a slice, then Atoi(change.Path[0]) is the index into the slice.
>>
>> On Friday, 14 July 2023 at 10:47:47 UTC+1 Mark wrote:
>>
>>> Hi Brian,
>>> Your code certainly identifies the different items.
>>> However, that's not a diff tool in the sense I mean.
>>> Unix diff and tools like it don't just say x[i] != y[i], they find the 
>>> longest common subsequences and in essence produce a series of edit 
>>> commands that would turn slice x into slice y.
>>> There are quite a few go diff tools that will do this, including my own 
>>> <https://pkg.go.dev/github.com/mark-summerfield/go-diff> based on 
>>> Python's difflib sequence matcher.
>>> What I want to do is find one that does this for slices of structs where 
>>> only one struct field is considered for comparison purposes.
>>>
>>> On Friday, July 14, 2023 at 10:00:34 AM UTC+1 Brian Candler wrote:
>>>
>>>> I forgot you wanted generics:
>>>> https://go.dev/play/p/PhGVjsWWTdB
>>>>
>>>> On Friday, 14 July 2023 at 09:47:21 UTC+1 Brian Candler wrote:
>>>>
>>>>> You seem to be saying "if the S field is different then I want to 
>>>>> consider these two structs different, and get pointers to the two 
>>>>> structs. 
>>>>> If the S field is the same then I want to skip the pair entirely". Is 
>>>>> that 
>>>>> right?
>>>>>
>>>>> The required semantics are not entirely clear, but it sounds like a 
>>>>> handful of lines of code to implement - there's no point importing and 
>>>>> learning a third party library.
>>>>>
>>>>> On the assumption that all the elements to be compared are in 
>>>>> corresponding positions in a and b:
>>>>> https://go.dev/play/p/Y71sLUpftzR
>>>>>
>>>>> On Friday, 14 July 2023 at 09:11:35 UTC+1 Mark wrote:
>>>>>
>>>>>> In fact the diff pkg mentioned above does work but is of no use to me 
>>>>>> since for each change it gives back only the field(s) used, not the 
>>>>>> original structs (or pointers to them), so I can't see any way back to 
>>>>>> the 
>>>>>> original structs (or their slice indexes).
>>>>>>
>>>>>> On Friday, July 14, 2023 at 8:58:41 AM UTC+1 Mark wrote:
>>>>>>
>>>>>>> What I really want to do is to be able to diff slices of structs on 
>>>>>>> the basis of one single field.
>>>>>>> For example, given:
>>>>>>> ```
>>>>>>> type Item struct {
>>>>>>>   I int
>>>>>>>   S string
>>>>>>> }
>>>>>>> ```
>>>>>>> and given `a` and `b` are both of type`[]Item`, I want to diff these 
>>>>>>> slices based purely on the `S` field, ignoring the `I` field.
>>>>>>>
>>>>>>> This diff pkg <https://pkg.go.dev/github.com/r3labs/diff/v3> claims 
>>>>>>> to be able to do this (something I'm testing, so I don't know either 
>>>>>>> way 
>>>>>>> yet), but in any case, it is incredibly slow.
>>>>>>>
>>>>>>> On Friday, July 14, 2023 at 8:31:39 AM UTC+1 Peter Galbavy wrote:
>>>>>>>
>>>>>>>> As a slight digression - I thought I was going mad, but 'slices' 
>>>>>>>> and 'maps' are new :-) Only in 1.21 though...
>>>>>>>>
>>>>>>>> Well, there is a lot of boiler plate that maps.Keys() will get rid 
>>>>>>>> of.
>>>>>>>>
>>>>>>>> On Thursday, 13 July 2023 at 10:06:01 UTC+1 Brian Candler wrote:
>>>>>>>>
>>>>>>>>> Structs are already comparable, but all fields must be the same:
>>&

[go-nuts] Re: Can a struct be made comparable?

2023-07-14 Thread 'Mark' via golang-nuts
Hi Brian,
Ah, thank you, that helped a lot.

On Friday, July 14, 2023 at 11:54:51 AM UTC+1 Brian Candler wrote:

> The 'diff' package you showed identifies the changed object index by means 
> of a "Path" attribute in the Changelog entry. If the top level object is a 
> slice, then Atoi(change.Path[0]) is the index into the slice.
>
> On Friday, 14 July 2023 at 10:47:47 UTC+1 Mark wrote:
>
>> Hi Brian,
>> Your code certainly identifies the different items.
>> However, that's not a diff tool in the sense I mean.
>> Unix diff and tools like it don't just say x[i] != y[i], they find the 
>> longest common subsequences and in essence produce a series of edit 
>> commands that would turn slice x into slice y.
>> There are quite a few go diff tools that will do this, including my own 
>> <https://pkg.go.dev/github.com/mark-summerfield/go-diff> based on 
>> Python's difflib sequence matcher.
>> What I want to do is find one that does this for slices of structs where 
>> only one struct field is considered for comparison purposes.
>>
>> On Friday, July 14, 2023 at 10:00:34 AM UTC+1 Brian Candler wrote:
>>
>>> I forgot you wanted generics:
>>> https://go.dev/play/p/PhGVjsWWTdB
>>>
>>> On Friday, 14 July 2023 at 09:47:21 UTC+1 Brian Candler wrote:
>>>
>>>> You seem to be saying "if the S field is different then I want to 
>>>> consider these two structs different, and get pointers to the two structs. 
>>>> If the S field is the same then I want to skip the pair entirely". Is that 
>>>> right?
>>>>
>>>> The required semantics are not entirely clear, but it sounds like a 
>>>> handful of lines of code to implement - there's no point importing and 
>>>> learning a third party library.
>>>>
>>>> On the assumption that all the elements to be compared are in 
>>>> corresponding positions in a and b:
>>>> https://go.dev/play/p/Y71sLUpftzR
>>>>
>>>> On Friday, 14 July 2023 at 09:11:35 UTC+1 Mark wrote:
>>>>
>>>>> In fact the diff pkg mentioned above does work but is of no use to me 
>>>>> since for each change it gives back only the field(s) used, not the 
>>>>> original structs (or pointers to them), so I can't see any way back to 
>>>>> the 
>>>>> original structs (or their slice indexes).
>>>>>
>>>>> On Friday, July 14, 2023 at 8:58:41 AM UTC+1 Mark wrote:
>>>>>
>>>>>> What I really want to do is to be able to diff slices of structs on 
>>>>>> the basis of one single field.
>>>>>> For example, given:
>>>>>> ```
>>>>>> type Item struct {
>>>>>>   I int
>>>>>>   S string
>>>>>> }
>>>>>> ```
>>>>>> and given `a` and `b` are both of type`[]Item`, I want to diff these 
>>>>>> slices based purely on the `S` field, ignoring the `I` field.
>>>>>>
>>>>>> This diff pkg <https://pkg.go.dev/github.com/r3labs/diff/v3> claims 
>>>>>> to be able to do this (something I'm testing, so I don't know either way 
>>>>>> yet), but in any case, it is incredibly slow.
>>>>>>
>>>>>> On Friday, July 14, 2023 at 8:31:39 AM UTC+1 Peter Galbavy wrote:
>>>>>>
>>>>>>> As a slight digression - I thought I was going mad, but 'slices' and 
>>>>>>> 'maps' are new :-) Only in 1.21 though...
>>>>>>>
>>>>>>> Well, there is a lot of boiler plate that maps.Keys() will get rid 
>>>>>>> of.
>>>>>>>
>>>>>>> On Thursday, 13 July 2023 at 10:06:01 UTC+1 Brian Candler wrote:
>>>>>>>
>>>>>>>> Structs are already comparable, but all fields must be the same:
>>>>>>>> https://go.dev/play/p/XwhSz4DEDwL
>>>>>>>>
>>>>>>>> I think your solution with function 'eq' is fine.  You can see the 
>>>>>>>> same thing in the standard library in slices.CompactFunc and 
>>>>>>>> slices.EqualFunc
>>>>>>>> https://pkg.go.dev/slices#CompactFunc
>>>>>>>> https://pkg.go.dev/slices#EqualFunc
>>>>>>>>
>>>>>>>> For the case of "ordered" rather than "comparable", have a look at 
>>>>>>>> slices.BinarySearchFunc and related functions.
>>>>>>>>
>>>>>>>> On Thursday, 13 July 2023 at 09:29:38 UTC+1 Mark wrote:
>>>>>>>>
>>>>>>>>> I have a package which has a function `Do[T comparable](a, b []T) 
>>>>>>>>> Result`.
>>>>>>>>> I have a struct:
>>>>>>>>> ```go
>>>>>>>>> type N struct {
>>>>>>>>>   x int
>>>>>>>>>   y int
>>>>>>>>>   t string
>>>>>>>>> }
>>>>>>>>> ```
>>>>>>>>> Is it possible to make `N` comparable; in particular by a field of 
>>>>>>>>> my choice, e.g., `t`?
>>>>>>>>>
>>>>>>>>> Or will I have to make, say, `DoFunc(a, b []N, eq func(i, j N) 
>>>>>>>>> bool) Result` with, say,
>>>>>>>>> `func eq(i, j N) { return i.t == j.t }`?
>>>>>>>>>
>>>>>>>>

-- 
You received this message because you are subscribed to the Google 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/eb4db5e8-598f-4ce9-bc6d-38f9c5ed6861n%40googlegroups.com.


[go-nuts] Re: Can a struct be made comparable?

2023-07-14 Thread 'Mark' via golang-nuts
Hi Brian,
Your code certainly identifies the different items.
However, that's not a diff tool in the sense I mean.
Unix diff and tools like it don't just say x[i] != y[i], they find the 
longest common subsequences and in essence produce a series of edit 
commands that would turn slice x into slice y.
There are quite a few go diff tools that will do this, including my own 
<https://pkg.go.dev/github.com/mark-summerfield/go-diff> based on Python's 
difflib sequence matcher.
What I want to do is find one that does this for slices of structs where 
only one struct field is considered for comparison purposes.

On Friday, July 14, 2023 at 10:00:34 AM UTC+1 Brian Candler wrote:

> I forgot you wanted generics:
> https://go.dev/play/p/PhGVjsWWTdB
>
> On Friday, 14 July 2023 at 09:47:21 UTC+1 Brian Candler wrote:
>
>> You seem to be saying "if the S field is different then I want to 
>> consider these two structs different, and get pointers to the two structs. 
>> If the S field is the same then I want to skip the pair entirely". Is that 
>> right?
>>
>> The required semantics are not entirely clear, but it sounds like a 
>> handful of lines of code to implement - there's no point importing and 
>> learning a third party library.
>>
>> On the assumption that all the elements to be compared are in 
>> corresponding positions in a and b:
>> https://go.dev/play/p/Y71sLUpftzR
>>
>> On Friday, 14 July 2023 at 09:11:35 UTC+1 Mark wrote:
>>
>>> In fact the diff pkg mentioned above does work but is of no use to me 
>>> since for each change it gives back only the field(s) used, not the 
>>> original structs (or pointers to them), so I can't see any way back to the 
>>> original structs (or their slice indexes).
>>>
>>> On Friday, July 14, 2023 at 8:58:41 AM UTC+1 Mark wrote:
>>>
>>>> What I really want to do is to be able to diff slices of structs on the 
>>>> basis of one single field.
>>>> For example, given:
>>>> ```
>>>> type Item struct {
>>>>   I int
>>>>   S string
>>>> }
>>>> ```
>>>> and given `a` and `b` are both of type`[]Item`, I want to diff these 
>>>> slices based purely on the `S` field, ignoring the `I` field.
>>>>
>>>> This diff pkg <https://pkg.go.dev/github.com/r3labs/diff/v3> claims to 
>>>> be able to do this (something I'm testing, so I don't know either way 
>>>> yet), 
>>>> but in any case, it is incredibly slow.
>>>>
>>>> On Friday, July 14, 2023 at 8:31:39 AM UTC+1 Peter Galbavy wrote:
>>>>
>>>>> As a slight digression - I thought I was going mad, but 'slices' and 
>>>>> 'maps' are new :-) Only in 1.21 though...
>>>>>
>>>>> Well, there is a lot of boiler plate that maps.Keys() will get rid of.
>>>>>
>>>>> On Thursday, 13 July 2023 at 10:06:01 UTC+1 Brian Candler wrote:
>>>>>
>>>>>> Structs are already comparable, but all fields must be the same:
>>>>>> https://go.dev/play/p/XwhSz4DEDwL
>>>>>>
>>>>>> I think your solution with function 'eq' is fine.  You can see the 
>>>>>> same thing in the standard library in slices.CompactFunc and 
>>>>>> slices.EqualFunc
>>>>>> https://pkg.go.dev/slices#CompactFunc
>>>>>> https://pkg.go.dev/slices#EqualFunc
>>>>>>
>>>>>> For the case of "ordered" rather than "comparable", have a look at 
>>>>>> slices.BinarySearchFunc and related functions.
>>>>>>
>>>>>> On Thursday, 13 July 2023 at 09:29:38 UTC+1 Mark wrote:
>>>>>>
>>>>>>> I have a package which has a function `Do[T comparable](a, b []T) 
>>>>>>> Result`.
>>>>>>> I have a struct:
>>>>>>> ```go
>>>>>>> type N struct {
>>>>>>>   x int
>>>>>>>   y int
>>>>>>>   t string
>>>>>>> }
>>>>>>> ```
>>>>>>> Is it possible to make `N` comparable; in particular by a field of 
>>>>>>> my choice, e.g., `t`?
>>>>>>>
>>>>>>> Or will I have to make, say, `DoFunc(a, b []N, eq func(i, j N) bool) 
>>>>>>> Result` with, say,
>>>>>>> `func eq(i, j N) { return i.t == j.t }`?
>>>>>>>
>>>>>>

-- 
You received this message because you are subscribed to the Google 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/51736175-1ecf-406b-acd4-29414f593d13n%40googlegroups.com.


[go-nuts] Re: Can a struct be made comparable?

2023-07-14 Thread 'Mark' via golang-nuts
In fact the diff pkg mentioned above does work but is of no use to me since 
for each change it gives back only the field(s) used, not the original 
structs (or pointers to them), so I can't see any way back to the original 
structs (or their slice indexes).

On Friday, July 14, 2023 at 8:58:41 AM UTC+1 Mark wrote:

> What I really want to do is to be able to diff slices of structs on the 
> basis of one single field.
> For example, given:
> ```
> type Item struct {
>   I int
>   S string
> }
> ```
> and given `a` and `b` are both of type`[]Item`, I want to diff these 
> slices based purely on the `S` field, ignoring the `I` field.
>
> This diff pkg <https://pkg.go.dev/github.com/r3labs/diff/v3> claims to be 
> able to do this (something I'm testing, so I don't know either way yet), 
> but in any case, it is incredibly slow.
>
> On Friday, July 14, 2023 at 8:31:39 AM UTC+1 Peter Galbavy wrote:
>
>> As a slight digression - I thought I was going mad, but 'slices' and 
>> 'maps' are new :-) Only in 1.21 though...
>>
>> Well, there is a lot of boiler plate that maps.Keys() will get rid of.
>>
>> On Thursday, 13 July 2023 at 10:06:01 UTC+1 Brian Candler wrote:
>>
>>> Structs are already comparable, but all fields must be the same:
>>> https://go.dev/play/p/XwhSz4DEDwL
>>>
>>> I think your solution with function 'eq' is fine.  You can see the same 
>>> thing in the standard library in slices.CompactFunc and slices.EqualFunc
>>> https://pkg.go.dev/slices#CompactFunc
>>> https://pkg.go.dev/slices#EqualFunc
>>>
>>> For the case of "ordered" rather than "comparable", have a look at 
>>> slices.BinarySearchFunc and related functions.
>>>
>>> On Thursday, 13 July 2023 at 09:29:38 UTC+1 Mark wrote:
>>>
>>>> I have a package which has a function `Do[T comparable](a, b []T) 
>>>> Result`.
>>>> I have a struct:
>>>> ```go
>>>> type N struct {
>>>>   x int
>>>>   y int
>>>>   t string
>>>> }
>>>> ```
>>>> Is it possible to make `N` comparable; in particular by a field of my 
>>>> choice, e.g., `t`?
>>>>
>>>> Or will I have to make, say, `DoFunc(a, b []N, eq func(i, j N) bool) 
>>>> Result` with, say,
>>>> `func eq(i, j N) { return i.t == j.t }`?
>>>>
>>>

-- 
You received this message because you are subscribed to the Google 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/63b52d59-e26e-4ceb-ae66-fa9ee82d303dn%40googlegroups.com.


[go-nuts] Re: Can a struct be made comparable?

2023-07-14 Thread 'Mark' via golang-nuts
What I really want to do is to be able to diff slices of structs on the 
basis of one single field.
For example, given:
```
type Item struct {
  I int
  S string
}
```
and given `a` and `b` are both of type`[]Item`, I want to diff these slices 
based purely on the `S` field, ignoring the `I` field.

This diff pkg <https://pkg.go.dev/github.com/r3labs/diff/v3> claims to be 
able to do this (something I'm testing, so I don't know either way yet), 
but in any case, it is incredibly slow.

On Friday, July 14, 2023 at 8:31:39 AM UTC+1 Peter Galbavy wrote:

> As a slight digression - I thought I was going mad, but 'slices' and 
> 'maps' are new :-) Only in 1.21 though...
>
> Well, there is a lot of boiler plate that maps.Keys() will get rid of.
>
> On Thursday, 13 July 2023 at 10:06:01 UTC+1 Brian Candler wrote:
>
>> Structs are already comparable, but all fields must be the same:
>> https://go.dev/play/p/XwhSz4DEDwL
>>
>> I think your solution with function 'eq' is fine.  You can see the same 
>> thing in the standard library in slices.CompactFunc and slices.EqualFunc
>> https://pkg.go.dev/slices#CompactFunc
>> https://pkg.go.dev/slices#EqualFunc
>>
>> For the case of "ordered" rather than "comparable", have a look at 
>> slices.BinarySearchFunc and related functions.
>>
>> On Thursday, 13 July 2023 at 09:29:38 UTC+1 Mark wrote:
>>
>>> I have a package which has a function `Do[T comparable](a, b []T) 
>>> Result`.
>>> I have a struct:
>>> ```go
>>> type N struct {
>>>   x int
>>>   y int
>>>   t string
>>> }
>>> ```
>>> Is it possible to make `N` comparable; in particular by a field of my 
>>> choice, e.g., `t`?
>>>
>>> Or will I have to make, say, `DoFunc(a, b []N, eq func(i, j N) bool) 
>>> Result` with, say,
>>> `func eq(i, j N) { return i.t == j.t }`?
>>>
>>

-- 
You received this message because you are subscribed to the Google 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/757d10ef-b748-4145-98f6-24849aaed627n%40googlegroups.com.


[go-nuts] Can a struct be made comparable?

2023-07-13 Thread 'Mark' via golang-nuts
I have a package which has a function `Do[T comparable](a, b []T) Result`.
I have a struct:
```go
type N struct {
  x int
  y int
  t string
}
```
Is it possible to make `N` comparable; in particular by a field of my 
choice, e.g., `t`?

Or will I have to make, say, `DoFunc(a, b []N, eq func(i, j N) bool) 
Result` with, say,
`func eq(i, j N) { return i.t == j.t }`?

-- 
You received this message because you are subscribed to the Google 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/139b01ed-14e7-451b-9b0e-c7d223c678aan%40googlegroups.com.


[go-nuts] Doc suggestion (& one const suggestion)

2023-05-02 Thread 'Mark' via golang-nuts
In the docs file modes are often shown in octal, e.g., `0600`.

Doc suggestion: update octal to use the modern unambiguous format, e.g., 
`0o600`.

Const suggestion: add at least one const to `os`, e.g., 
```go
const ModeUserRW = 0o600
// plus any one or two others that are really common?
```
If the const it added it should be used on the docs rather than raw `0o600`.

-- 
You received this message because you are subscribed to the Google 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/a8699162-3256-4d51-bba4-87135e5f1b19n%40googlegroups.com.


Re: [go-nuts] Which tool provide's the Go playground's import handling...

2023-01-06 Thread 'Mark' via golang-nuts
Thanks, that's just what I needed :-)

On Friday, January 6, 2023 at 8:21:02 AM UTC kortschak wrote:

> On Fri, 2023-01-06 at 00:13 -0800, 'Mark' via golang-nuts wrote:
> > If I visit the Go playground and change the body of `main()` to, say,
> > `fmt.Println("hello", math.Abs(-5))` and then click Run, the `import
> > "fmt"` line is _automatically_ corrected to be `import
> > (\n\t"fmt"\n\t"math"\n)`. I'd like to be able to use this
> > functionality so that I can set my editor to do "fiximports" and then
> > "gofmt" rather than just "gofmt" as now. But I don't know what the
> > tool is that does this?
>
> https://pkg.go.dev/golang.org/x/tools/cmd/goimports
>
>

-- 
You received this message because you are subscribed to the Google 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/0a0d14e9-b1ed-4bef-8785-5ca29778b332n%40googlegroups.com.


[go-nuts] Which tool provide's the Go playground's import handling...

2023-01-06 Thread 'Mark' via golang-nuts
If I visit the Go playground  and change the body of 
`main()` to, say, `fmt.Println("hello", math.Abs(-5))` and then click Run, 
the `import "fmt"` line is _automatically_ corrected to be `import 
(\n\t"fmt"\n\t"math"\n)`. I'd like to be able to use this functionality so 
that I can set my editor to do "fiximports" and then "gofmt" rather than 
just "gofmt" as now. But I don't know what the tool is that does 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/9d6b1181-6332-492b-a9cc-93b8953882bfn%40googlegroups.com.


Re: [go-nuts] How to fix an awful marshal reflection hack

2022-12-01 Thread 'Mark' via golang-nuts
The reason there's no nullable in the real code is that it isn't needed 
there: if the field is to a pointer variable (e.g., *string), then I call 
hack() and that adds the '?' to the string so no need for a nullable bool; 
otherwise for non-pointers it falls through to the normal processing. So 
the complete -- and working -- code is in the repo and go test works. But 
replacing the call to hack() with kind = field.Type().Elem().Kind() breaks 
the tests.

On Thursday, December 1, 2022 at 1:09:50 PM UTC Marvin Renich wrote:

> * 'Mark' via golang-nuts  [221201 05:17]:
> > I tried that and it works in the playground, and I added more types and 
> it 
> > still works in the playground <https://go.dev/play/p/Yxzj4tAAGhM>.
> > But in my program it still doesn't work:-( 
> > The actual code is here tdb-go <
> https://github.com/mark-summerfield/tdb-go> 
> > in the file marshal.go from line 133 function marshalTableMetaData().
> > If you run: go test it all works; but if you replace the call to hack() 
> and 
> > use nullable as you did in the playground, some of the tests fail.
>
> You don't show the code that doesn't work (i.e. with nullable). Did you
> make a typo like you did in your code below?
>
> > On Thursday, December 1, 2022 at 9:45:48 AM UTC kortschak wrote:
> > 
> > > On Thu, 2022-12-01 at 00:33 -0800, 'Mark' via golang-nuts wrote:
> > > > Thanks. I've now tried that as follows:
> > > >
> > > > fmt.Printf("@@: %T %v\n", field, field)
> > > > kind = field.Type().Elem().Kind()
> > > > fmt.Printf("##: %T %v\n", field, field)
>
> Note that in both Printf statements, you are using field rather than
> kind. If the two Printf's gave different results, I would consider it a
> compiler bug (a really egregious one!).
>
> > > > In every case the output for kind before and after was identical.
> > > > (Naturally, I tried without the print statements too.) And, of course
> > > > the tests fail. So I'm _still_ using the awful hack!
> > > >
> > >
> > > Doesn't this do what you want?
> > >
> > > https://go.dev/play/p/7jUw_iW8B_8
>
> ...Marvin
>
>

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


Re: [go-nuts] How to fix an awful marshal reflection hack

2022-12-01 Thread 'Mark' via golang-nuts
I tried that and it works in the playground, and I added more types and it 
still works in the playground <https://go.dev/play/p/Yxzj4tAAGhM>.
But in my program it still doesn't work:-( 
The actual code is here tdb-go <https://github.com/mark-summerfield/tdb-go> 
in the file marshal.go from line 133 function marshalTableMetaData().
If you run: go test it all works; but if you replace the call to hack() and 
use nullable as you did in the playground, some of the tests fail.

On Thursday, December 1, 2022 at 9:45:48 AM UTC kortschak wrote:

> On Thu, 2022-12-01 at 00:33 -0800, 'Mark' via golang-nuts wrote:
> > Thanks. I've now tried that as follows:
> >
> > fmt.Printf("@@: %T %v\n", field, field)
> > kind = field.Type().Elem().Kind()
> > fmt.Printf("##: %T %v\n", field, field)
> >
> > In every case the output for kind before and after was identical.
> > (Naturally, I tried without the print statements too.) And, of course
> > the tests fail. So I'm _still_ using the awful hack!
> >
>
> Doesn't this do what you want?
>
> https://go.dev/play/p/7jUw_iW8B_8
>
>

-- 
You received this message because you are subscribed to the Google 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/74538c6d-a18a-4ca6-b8a9-4cb4fca44f58n%40googlegroups.com.


Re: [go-nuts] How to fix an awful marshal reflection hack

2022-12-01 Thread 'Mark' via golang-nuts
Thanks. I've now tried that as follows:

fmt.Printf("@@: %T %v\n", field, field)
kind = field.Type().Elem().Kind()
fmt.Printf("##: %T %v\n", field, field)

In every case the output for kind before and after was identical. 
(Naturally, I tried without the print statements too.) And, of course the 
tests fail. So I'm _still_ using the awful hack!

On Wednesday, November 30, 2022 at 5:30:24 PM UTC bse...@computer.org wrote:

> On Wed, Nov 30, 2022 at 10:17 AM 'Mark' via golang-nuts <
> golan...@googlegroups.com> wrote:
>
>> Yes, I'd already tried that (that's what I started with) and 
>> unfortunately it doesn't work.
>>
>
> It fails if field.Elem() is nil. Try this:
>
>   kind = field.Type().Elem().Kind()
>  
>
>>
>> On Wednesday, November 30, 2022 at 3:37:47 PM UTC bse...@computer.org 
>> wrote:
>>
>>> On Wed, Nov 30, 2022 at 5:29 AM 'Mark' via golang-nuts <
>>> golan...@googlegroups.com> wrote:
>>>
>>>> I have this code which works but has a horrible hack:
>>>> ...
>>>> nullable := false
>>>> kind := field.Kind() // field's type is reflect.Value
>>>> if kind == reflect.Ptr {
>>>>
>>>
>>> This should work:
>>>
>>> kind = field.Elem().Kind()
>>>
>>>
>>>  
>>>
>>>> // FIXME How can I improve upon this truly awful hack?
>>>> switch field.Type().String() {
>>>> case "*int", "*int8", "*uint8", "*int16", "*uint16", "*int32", 
>>>> "*uint32", "*int64", "*uint64":
>>>> kind = reflect.Int
>>>> case "*float32", "*float64":
>>>> kind = reflect.Float64
>>>> }
>>>> nullable = true
>>>> }
>>>> switch kind {
>>>> case reflect.Bool:
>>>> out.WriteString("bool")
>>>> case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, 
>>>> reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, 
>>>> reflect.Uint32, 
>>>> reflect.Uint64:
>>>> out.WriteString("int")
>>>> case reflect.Float32, reflect.Float64:
>>>> out.WriteString("real")
>>>> ...
>>>> if nullable {
>>>> out.WriteByte('?')
>>>> }
>>>> What is the correct way to achieve what I'm aiming for?
>>>>
>>>> -- 
>>>> You received this message because you are subscribed 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/5ff4b6f6-405c-4ca5-9299-7c15e1d5c424n%40googlegroups.com
>>>>  
>>>> <https://groups.google.com/d/msgid/golang-nuts/5ff4b6f6-405c-4ca5-9299-7c15e1d5c424n%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...@googlegroups.com.
>>
> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/golang-nuts/c2d154f2-b425-4cc9-a015-af30f4dc9de2n%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/c2d154f2-b425-4cc9-a015-af30f4dc9de2n%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/afa700de-926f-42b3-a2cd-18b9c1c12438n%40googlegroups.com.


Re: [go-nuts] How to fix an awful marshal reflection hack

2022-11-30 Thread 'Mark' via golang-nuts
Yes, I'd already tried that (that's what I started with) and unfortunately 
it doesn't work.

On Wednesday, November 30, 2022 at 3:37:47 PM UTC bse...@computer.org wrote:

> On Wed, Nov 30, 2022 at 5:29 AM 'Mark' via golang-nuts <
> golan...@googlegroups.com> wrote:
>
>> I have this code which works but has a horrible hack:
>> ...
>> nullable := false
>> kind := field.Kind() // field's type is reflect.Value
>> if kind == reflect.Ptr {
>>
>
> This should work:
>
> kind = field.Elem().Kind()
>
>
>  
>
>> // FIXME How can I improve upon this truly awful hack?
>> switch field.Type().String() {
>> case "*int", "*int8", "*uint8", "*int16", "*uint16", "*int32", 
>> "*uint32", "*int64", "*uint64":
>> kind = reflect.Int
>> case "*float32", "*float64":
>> kind = reflect.Float64
>> }
>> nullable = true
>> }
>> switch kind {
>> case reflect.Bool:
>> out.WriteString("bool")
>> case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, 
>> reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, 
>> reflect.Uint64:
>> out.WriteString("int")
>> case reflect.Float32, reflect.Float64:
>> out.WriteString("real")
>> ...
>> if nullable {
>> out.WriteByte('?')
>> }
>> What is the correct way to achieve what I'm aiming for?
>>
>> -- 
>> You received this message because you are subscribed 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/5ff4b6f6-405c-4ca5-9299-7c15e1d5c424n%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/5ff4b6f6-405c-4ca5-9299-7c15e1d5c424n%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/c2d154f2-b425-4cc9-a015-af30f4dc9de2n%40googlegroups.com.


[go-nuts] How to fix an awful marshal reflection hack

2022-11-30 Thread 'Mark' via golang-nuts
I have this code which works but has a horrible hack:
...
nullable := false
kind := field.Kind() // field's type is reflect.Value
if kind == reflect.Ptr {
// FIXME How can I improve upon this truly awful hack?
switch field.Type().String() {
case "*int", "*int8", "*uint8", "*int16", "*uint16", "*int32", 
"*uint32", "*int64", "*uint64":
kind = reflect.Int
case "*float32", "*float64":
kind = reflect.Float64
}
nullable = true
}
switch kind {
case reflect.Bool:
out.WriteString("bool")
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, 
reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, 
reflect.Uint64:
out.WriteString("int")
case reflect.Float32, reflect.Float64:
out.WriteString("real")
...
if nullable {
out.WriteByte('?')
}
What is the correct way to achieve what I'm aiming for?

-- 
You received this message because you are subscribed to the Google 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/5ff4b6f6-405c-4ca5-9299-7c15e1d5c424n%40googlegroups.com.


[go-nuts] Re: How to read struct field names from an empty slice of structs

2022-11-21 Thread 'Mark' via golang-nuts
After struggling, I finally solved it; playground 
<https://go.dev/play/p/w0OSFCX10Rx>

On Monday, November 21, 2022 at 10:55:06 AM UTC Mark wrote:

> I have a two level general-purpose data structure: a struct containing one 
> or more slices of structs.
> I want to be able to use reflection to populate this, but as a first step 
> I want to extract the 
> "table names" (i.e., the names of the fields of the outer struct), and the 
> "field names" (the names of each field in each of the inner structs).
> Below is as far as I've got: it correctly finds the table names (including 
> their tag alternatives), but I can't work out how to access the field 
> names...
>
> playground <https://go.dev/play/p/lAxfwwD9x83>

-- 
You received this message because you are subscribed to the Google 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/e2a46498-7f57-418f-a258-0868fa93f7a5n%40googlegroups.com.


[go-nuts] How to read struct field names from an empty slice of structs

2022-11-21 Thread 'Mark' via golang-nuts
I have a two level general-purpose data structure: a struct containing one 
or more slices of structs.
I want to be able to use reflection to populate this, but as a first step I 
want to extract the 
"table names" (i.e., the names of the fields of the outer struct), and the 
"field names" (the names of each field in each of the inner structs).
Below is as far as I've got: it correctly finds the table names (including 
their tag alternatives), but I can't work out how to access the field 
names...

playground 

-- 
You received this message because you are subscribed to the Google 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/c1f828b3-119d-4f78-bd4a-1d0be71d9c1an%40googlegroups.com.


Re: [go-nuts] Is it possible to switch on type T in a generic function?

2022-11-09 Thread 'Mark' via golang-nuts
Thank you! I've now switched to using any as you suggested & also use 
strings.Builder.

On Wednesday, November 9, 2022 at 4:33:48 PM UTC dun...@harris3.org wrote:

> > Interestingly, I couldn't put the asStr() code in the String() function 
> since doing so produced this error:
> > 
> > invalid operation: cannot use type assertion on type parameter value 
> element (variable of type T constrained by comparable)
>
> You need to convert to "any": https://go.dev/play/p/1pMhs22S-8P
>
> P.S. It would be better to use https://pkg.go.dev/strings#Builder for 
> building a string
>
> On Tuesday, 8 November 2022 at 13:09:51 UTC Mark wrote:
>
>> Thanks for your help and very interesting ideas. In the end I used this:
>>
>> type Set[T comparable] map[T]struct{}
>>
>> func New[T comparable](elements ...T) Set[T] {
>> set := make(Set[T], len(elements))
>> for _, element := range elements {
>> set[element] = struct{}{}
>> }
>> return set
>> }
>>
>> func (me Set[T]) String() string {
>> elements := make([]T, 0, len(me))
>> for element := range me {
>> elements = append(elements, element)
>> }
>> sort.Slice(elements, func(i, j int) bool {
>> return less(elements[i], elements[j])
>> })
>> s := "{"
>> sep := ""
>> for _, element := range elements {
>> s += sep + asStr(element)
>>
>> sep = " "
>> }
>> return s + "}"
>> }
>>
>> func asStr(x any) string {
>> if s, ok := x.(string); ok {
>> return fmt.Sprintf("%q", s)
>> }
>> return fmt.Sprintf("%v", x)
>> }
>>
>> func less(a, b any) bool {
>> switch x := a.(type) {
>> case int:
>> return x < b.(int)
>> case float64:
>> return x < b.(float64)
>> case string:
>> return x < b.(string)
>> default:
>> return fmt.Sprintf("%v", a) < fmt.Sprintf("%v", b)
>> }
>> }
>>
>> Interestingly, I couldn't put the asStr() code in the String() function 
>> since doing so produced this error:
>>
>> invalid operation: cannot use type assertion on type parameter value 
>> element (variable of type T constrained by comparable)
>>
>> Anyway, I'm happy that it all works now. (I know I ought to include every 
>> int & float32, but this is enough for now).
>>
>>
>>
>> On Tuesday, November 8, 2022 at 11:29:34 AM UTC rog wrote:
>>
>>> If you're sure that T is an int or a string, then why not constrain it 
>>> as such? https://go.dev/play/p/1kT6EacMHco
>>>
>>> You could go further and constrain it to allow any type with ordering 
>>> defined: https://go.dev/play/p/il5koj1RPkh
>>>
>>> If you want to allow any kind of comparable key in your set, one could 
>>> observe that essentially you're trying to solve the same problem that the 
>>> fmt package is solving when it converts maps to string. It uses the 
>>> internal fmtsort <https://pkg.go.dev/internal/fmtsort> package, which, 
>>> as luck would have it, has been factored out into an externally 
>>> available package 
>>> <https://pkg.go.dev/github.com/rogpeppe/go-internal/fmtsort>. So you 
>>> could do this: https://go.dev/play/p/oKTGSm_o22a
>>>
>>> To answer the specific question you asked, there is an issue that tracks 
>>> the ability to do a switch directly on a type parameter: 
>>> https://github.com/golang/go/issues/45380
>>>
>>> But you can also work around the lack of that feature by doing something 
>>> like this: https://go.dev/play/p/3C2a61Ojbxs
>>>
>>> Hope this helps,
>>>
>>>   rog.
>>>
>>>
>>> On Tue, 8 Nov 2022 at 08:53, 'Mark' via golang-nuts <
>>> golan...@googlegroups.com> wrote:
>>>
>>>> Given a function:
>>>>
>>>> func F[T comparable](a T) {
>>>> }
>>>>
>>>> is it possible to check T's type inside F?
>>>>
>>>> My use case is that I have a function with signature G[T comparable](x 
>>>> []T) and inside G I want to sort the elements in slice x where T could be 
>>>> int or string.
>>>>
>>>> This arises in a tiny generic set module I've created: 
>>>> https://github.com/mark-summerfield/gset
>>>

Re: [go-nuts] Is it possible to switch on type T in a generic function?

2022-11-08 Thread 'Mark' via golang-nuts
Thanks for your help and very interesting ideas. In the end I used this:

type Set[T comparable] map[T]struct{}

func New[T comparable](elements ...T) Set[T] {
set := make(Set[T], len(elements))
for _, element := range elements {
set[element] = struct{}{}
}
return set
}

func (me Set[T]) String() string {
elements := make([]T, 0, len(me))
for element := range me {
elements = append(elements, element)
}
sort.Slice(elements, func(i, j int) bool {
return less(elements[i], elements[j])
})
s := "{"
sep := ""
for _, element := range elements {
s += sep + asStr(element)
sep = " "
}
return s + "}"
}

func asStr(x any) string {
if s, ok := x.(string); ok {
return fmt.Sprintf("%q", s)
}
return fmt.Sprintf("%v", x)
}

func less(a, b any) bool {
switch x := a.(type) {
case int:
return x < b.(int)
case float64:
return x < b.(float64)
case string:
return x < b.(string)
default:
return fmt.Sprintf("%v", a) < fmt.Sprintf("%v", b)
}
}

Interestingly, I couldn't put the asStr() code in the String() function 
since doing so produced this error:

invalid operation: cannot use type assertion on type parameter value 
element (variable of type T constrained by comparable)

Anyway, I'm happy that it all works now. (I know I ought to include every 
int & float32, but this is enough for now).



On Tuesday, November 8, 2022 at 11:29:34 AM UTC rog wrote:

> If you're sure that T is an int or a string, then why not constrain it as 
> such? https://go.dev/play/p/1kT6EacMHco
>
> You could go further and constrain it to allow any type with ordering 
> defined: https://go.dev/play/p/il5koj1RPkh
>
> If you want to allow any kind of comparable key in your set, one could 
> observe that essentially you're trying to solve the same problem that the 
> fmt package is solving when it converts maps to string. It uses the 
> internal fmtsort <https://pkg.go.dev/internal/fmtsort> package, which, as 
> luck would have it, has been factored out into an externally available 
> package <https://pkg.go.dev/github.com/rogpeppe/go-internal/fmtsort>. So 
> you could do this: https://go.dev/play/p/oKTGSm_o22a
>
> To answer the specific question you asked, there is an issue that tracks 
> the ability to do a switch directly on a type parameter: 
> https://github.com/golang/go/issues/45380
>
> But you can also work around the lack of that feature by doing something 
> like this: https://go.dev/play/p/3C2a61Ojbxs
>
> Hope this helps,
>
>   rog.
>
>
> On Tue, 8 Nov 2022 at 08:53, 'Mark' via golang-nuts <
> golan...@googlegroups.com> wrote:
>
>> Given a function:
>>
>> func F[T comparable](a T) {
>> }
>>
>> is it possible to check T's type inside F?
>>
>> My use case is that I have a function with signature G[T comparable](x 
>> []T) and inside G I want to sort the elements in slice x where T could be 
>> int or string.
>>
>> This arises in a tiny generic set module I've created: 
>> https://github.com/mark-summerfield/gset
>> In the String() method I want to return a string with the elements sorted 
>> (for human readability and for testing convenience); but at the moment I 
>> can only do this by converting all elements to strings and sorting them 
>> which isn't good for ints.
>>
>> -- 
>> You received this message because you are subscribed 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/e746f065-24fa-474a-90ec-2d8367bf3e3bn%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/e746f065-24fa-474a-90ec-2d8367bf3e3bn%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/dea0057c-fd75-4a05-a171-0a77bbd1d051n%40googlegroups.com.


Re: [go-nuts] Is it possible to switch on type T in a generic function?

2022-11-08 Thread 'Mark' via golang-nuts
I see that your example works, but I can't see how to adapt it to my use 
case.

type Set[T comparable] map[T]struct{}

func New[T comparable](elements ...T) Set[T] {
set := make(Set[T], len(elements))
for _, element := range elements {
set[element] = struct{}{}
}
return set
}

func (me Set[T]) String() string {
// Want to sort by T < T //
elements := make([]string, 0, len(me))
for element := range me {
elements = append(elements, fmt.Sprintf("%#v", element))
}
sort.Strings(elements)
/
s := "{"
sep := ""
for _, element := range elements {
s += fmt.Sprintf("%s%s", sep, element)
sep = " "
}
return s + "}"
}

On Tuesday, November 8, 2022 at 9:19:48 AM UTC Jan Mercl wrote:

> On Tue, Nov 8, 2022 at 9:53 AM 'Mark' via golang-nuts
>  wrote:
>
> > Given a function:
> >
> > func F[T comparable](a T) {
> > }
> >
> > is it possible to check T's type inside F?
> >
> > My use case is that I have a function with signature G[T comparable](x 
> []T) and inside G I want to sort the elements in slice x where T could be 
> int or string.
>
> https://go.dev/play/p/zxQYVvOMX35 ?
>

-- 
You received this message because you are subscribed to the Google 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/577c056e-bf3f-4002-b431-f73aeda75a6dn%40googlegroups.com.


[go-nuts] Is it possible to switch on type T in a generic function?

2022-11-08 Thread 'Mark' via golang-nuts
Given a function:

func F[T comparable](a T) {
}

is it possible to check T's type inside F?

My use case is that I have a function with signature G[T comparable](x []T) 
and inside G I want to sort the elements in slice x where T could be int or 
string.

This arises in a tiny generic set module I've created: 
https://github.com/mark-summerfield/gset
In the String() method I want to return a string with the elements sorted 
(for human readability and for testing convenience); but at the moment I 
can only do this by converting all elements to strings and sorting them 
which isn't good for ints.

-- 
You received this message because you are subscribed to the Google 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/e746f065-24fa-474a-90ec-2d8367bf3e3bn%40googlegroups.com.


Re: [go-nuts] How do I set a pkg's version?

2022-11-02 Thread 'Mark' via golang-nuts
Oh, except that debug.BuildInfo (unsurprisingly) is only available in debug 
not release builds. So I guess the answer is that there isn't any nice way 
to do it.

On Wednesday, November 2, 2022 at 8:31:29 AM UTC Mark wrote:

> I hadn't realised about debug.BuildInfo - thanks!
>
> On Tuesday, November 1, 2022 at 9:15:02 PM UTC axel.wa...@googlemail.com 
> wrote:
>
>> It feels like an oversight not to mention debug.BuildInfo 
>> <https://pkg.go.dev/runtime/debug@go1.19.2#BuildInfo> here. No CI/CD or 
>> manual build steps required.
>>
>> On Tue, Nov 1, 2022 at 9:55 PM Chris Burkert  wrote:
>>
>>> During CI/CD we create a json file with a few details (git tag, branch, 
>>> hash, date, time). Afterwards we compile Go Code which embeds this file 
>>> into the binary. During runtime flags like --version print the json.
>>>
>>> Note that this is about the version of some binary - not the version of 
>>> a package. However, you could embed go.mod. But there may be better ways.
>>>
>>> Hope this helps.
>>>
>>> 'Mark' via golang-nuts  schrieb am Di. 1. 
>>> Nov. 2022 um 16:34:
>>>
>>>> I am creating a pkg.
>>>> It has a `go.mod` file:
>>>> ```
>>>> module github.com/.../mypkg
>>>>
>>>> go 1.19
>>>> ```
>>>> And code files with functions in .go files all in the mypkg pkg.
>>>>
>>>> How do I specify which version the mypkg pkg is? I know about using `$ 
>>>> git tag vX.Y.Z` and `$ git push origin vX.Y.Z`, but is there any way I can 
>>>> have this version in a file that can be accessed at build time or runtime?
>>>>
>>>> -- 
>>>> You received this message because you are subscribed 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/0a16b738-59e5-4885-90c8-cd168e308623n%40googlegroups.com
>>>>  
>>>> <https://groups.google.com/d/msgid/golang-nuts/0a16b738-59e5-4885-90c8-cd168e308623n%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...@googlegroups.com.
>>>
>> To view this discussion on the web visit 
>>> https://groups.google.com/d/msgid/golang-nuts/CALWqRZov4r%2BN2FiZug5mmwUwhYcvf08922UQU%3DMqfJKLFT8dBg%40mail.gmail.com
>>>  
>>> <https://groups.google.com/d/msgid/golang-nuts/CALWqRZov4r%2BN2FiZug5mmwUwhYcvf08922UQU%3DMqfJKLFT8dBg%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/09ab0bb7-3c1e-48da-a5c1-79c0d3f1968dn%40googlegroups.com.


[go-nuts] Trying to create a test app for a library package

2022-11-02 Thread 'Mark' via golang-nuts
I have this layout:
```
mylib/
mylib/go.mod # module github.com/me/mylib
mylib/mylib.go
mylib/mylib_test.go
```
All this works fine, with both .go files being in the same pkg: mylib.

However, there are some tests that I can't really do using the test module 
because they write to stdout. So I want to create an exe for regression 
testing.

In particular I want the regression tester to be in package main (just like 
an app that uses mylib).

I've tried this layout:
```
mylib/
mylib/go.mod # module github.com/me/mylib
mylib/mylib.go
mylib/mylib_test.go
mylib/tester/tester.go
```
But I can't get the import to work:
```go
package main

import (
"fmt"
"mylib"
)

func main() {
parser := mylib.Parser()
fmt.Println(parser.AppName(), parser.Version())
}
```
The error I get is `tester/tester.go:8:2: package garg is not in GOROOT`, 
which is perfectly correct.
So then I tried to change the import to `../mylib`, but that also produces 
an error, `tester/tester.go:8:2: "../mylib" is relative, but relative 
import paths are not supported in module mode`

Is what I'm trying to do possible? If so, how? If not, what d'you recommend?

-- 
You received this message because you are subscribed to the Google 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/b9511da6-2e48-44ec-a16a-7985614632f7n%40googlegroups.com.


Re: [go-nuts] How do I set a pkg's version?

2022-11-02 Thread 'Mark' via golang-nuts
I hadn't realised about debug.BuildInfo - thanks!

On Tuesday, November 1, 2022 at 9:15:02 PM UTC axel.wa...@googlemail.com 
wrote:

> It feels like an oversight not to mention debug.BuildInfo 
> <https://pkg.go.dev/runtime/debug@go1.19.2#BuildInfo> here. No CI/CD or 
> manual build steps required.
>
> On Tue, Nov 1, 2022 at 9:55 PM Chris Burkert  wrote:
>
>> During CI/CD we create a json file with a few details (git tag, branch, 
>> hash, date, time). Afterwards we compile Go Code which embeds this file 
>> into the binary. During runtime flags like --version print the json.
>>
>> Note that this is about the version of some binary - not the version of a 
>> package. However, you could embed go.mod. But there may be better ways.
>>
>> Hope this helps.
>>
>> 'Mark' via golang-nuts  schrieb am Di. 1. 
>> Nov. 2022 um 16:34:
>>
>>> I am creating a pkg.
>>> It has a `go.mod` file:
>>> ```
>>> module github.com/.../mypkg
>>>
>>> go 1.19
>>> ```
>>> And code files with functions in .go files all in the mypkg pkg.
>>>
>>> How do I specify which version the mypkg pkg is? I know about using `$ 
>>> git tag vX.Y.Z` and `$ git push origin vX.Y.Z`, but is there any way I can 
>>> have this version in a file that can be accessed at build time or runtime?
>>>
>>> -- 
>>> You received this message because you are subscribed 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/0a16b738-59e5-4885-90c8-cd168e308623n%40googlegroups.com
>>>  
>>> <https://groups.google.com/d/msgid/golang-nuts/0a16b738-59e5-4885-90c8-cd168e308623n%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...@googlegroups.com.
>>
> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/golang-nuts/CALWqRZov4r%2BN2FiZug5mmwUwhYcvf08922UQU%3DMqfJKLFT8dBg%40mail.gmail.com
>>  
>> <https://groups.google.com/d/msgid/golang-nuts/CALWqRZov4r%2BN2FiZug5mmwUwhYcvf08922UQU%3DMqfJKLFT8dBg%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/ac35d44d-5795-45d3-9b46-5bfd643d2a34n%40googlegroups.com.


[go-nuts] How do I set a pkg's version?

2022-11-01 Thread 'Mark' via golang-nuts
I am creating a pkg.
It has a `go.mod` file:
```
module github.com/.../mypkg

go 1.19
```
And code files with functions in .go files all in the mypkg pkg.

How do I specify which version the mypkg pkg is? I know about using `$ git 
tag vX.Y.Z` and `$ git push origin vX.Y.Z`, but is there any way I can have 
this version in a file that can be accessed at build time or runtime?

-- 
You received this message because you are subscribed to the Google 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/0a16b738-59e5-4885-90c8-cd168e308623n%40googlegroups.com.


Re: [go-nuts] Go build speed dependent on time after source modification

2021-11-05 Thread Mark Fletcher
On Fri, Nov 5, 2021 at 5:10 AM Alberto Donizetti 
wrote:

> Could be due to https://github.com/golang/go/issues/48496
> Should be fixed on tip, but 1.17 is affected.
>
>
Thanks for this pointer. I just tested this and it made a huge difference.
For a change to a single file, compiling on 1.17.2 takes ~14 seconds. On
tip, it takes ~5 seconds.

Mark

-- 
You received this message because you are subscribed to the Google 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/CADOuSDFZitYtzxg2tuj9nJaDdQukM0K2NdXEfHdX5Ud%3DppdXFQ%40mail.gmail.com.


Re: [go-nuts] Go build speed dependent on time after source modification

2021-11-04 Thread Mark Fletcher
On Thu, Nov 4, 2021 at 10:25 AM Brian Hatfield  wrote:

> This seems a little like you might have a background compilation process
> occurring which is populating the build cache. What editor environment are
> you using? Is it possible it is effectively running compilations on your
> code, whether via IDE support, indirectly via linters, or other on-save
> actions?
>
>>
>>
Hmm, well I think you're right. I use VSCode, which runs gopls. It never
occured to me that gopls would run a compile, but I guess in hindsight it
makes sense. If I shut down VSCode and instead edit the file using vi, I
get consistent 16 second compile times regardless of how long I wait. So,
thanks for the suggestion. I still don't understand why my compile times
are the same between the i9 and M1 Max, but I guess I need to do some more
research.

Thanks,
Mark

-- 
You received this message because you are subscribed to the Google 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/CADOuSDGmck2ArVxfRC6tsP%3D_OYO0jGA-Xd%3D0dNRkm%2BYW7n1WZg%40mail.gmail.com.


[go-nuts] Go build speed dependent on time after source modification

2021-11-04 Thread Mark Fletcher
I recently migrated from a 2019 i9 Macbook Pro to a new M1 Max Macbook Pro 
(64GB on both machines), and to my surprise, my go build times ended up 
being the same. I started to do some research, and I've found a curious 
behavior that I'm hoping someone can shed some light on. This is with go 
1.17.2, vendored dependencies, in a large project.

For my test, I'm just changing a fmt.Printf() in one source file, to 
hopefully avoid any caching.

Here's the strange thing. If I do a 'go build' within ~12 seconds of saving 
that change, my build time is about 16 seconds. If I save that change and 
wait at least 13 seconds, my build time drops to about 2 seconds. This is 
repeatable. I run the binary after each build, and can see the changed 
printf(), so I know it's being compiled.

I then looked at the output of 'go build -x' in each instance, and there 
are a couple of differences. In the case where I don't wait after saving, 
at the start of the build, it creates a _gomod_.go file. And then, it runs 
a compile, which takes the majority of the 16 seconds. In the case where I 
wait at least 13 seconds after saving the source file, the build does 
neither of these steps.

Any thoughts/suggestions would be appreciated.

Mark

-- 
You received this message because you are subscribed to the Google 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/7fcd831f-b89e-4319-9190-fba199efd5d0n%40googlegroups.com.


Re: [go-nuts] Why isn't go more popular?

2021-08-06 Thread Mark Sinoberg
can not agree more with u, go cool.

在2021年8月6日星期五 UTC+8 上午10:28:03 写道:

> On Thu, Aug 5, 2021 at 7:20 PM Santi Ferra
>  wrote:
> >
> > When you see the ranking of the most liked programming languages, go is 
> near c++, a really "hated app". But since is efficient and produces really 
> clean code, why no wants like it ?
>
> What rankings are you looking at?
>
> 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/e3cd8eb3-3c63-45d6-a6dd-9272ceeb8566n%40googlegroups.com.


[go-nuts] Re: Writing bitmap data to a canvas with WebAssembly

2020-07-24 Thread Mark Farnan
Little old, but this might also help. 

 A while back I built a helper package to deal with these issues for canvas 
rendering from Go.  

https://github.com/markfarnan/go-canvas  

I'm currently working on it to add  WebGL support & get it working in 
TinyGo (some issues still).

Regards

Mark.



On Sunday, 22 March 2020 at 09:08:40 UTC+1 Scott Pakin wrote:

> I figure I ought to follow up with some results.  First, I got the 
> suggested approach of local render + js.CopyBytesToJS 
> <https://golang.org/pkg/syscall/js/#CopyBytesToJS> + update canvas from 
> image to work, so thanks, Agniva and Howard!  Second, for the benefit of 
> future readers of this thread, one thing that wasn't obvious to me is that 
> one needs to render the image data in a browser-recognizable image format—I 
> used PNG <https://en.wikipedia.org/wiki/Portable_Network_Graphics>—*not* 
> raw {red, green, blue, alpha} bytes as is needed when writing directly to a 
> canvas <https://www.w3schools.com/tags/tag_canvas.asp>'s image data.  
> Third, I used JavaScript code like the following to update an invisible 
> img <https://www.w3schools.com/tags/tag_img.asp> then copy the image data 
> from there to a visible canvas:
>
> function copyBytesToCanvas(data) {
> let blob = new Blob([data], {"type": "image/png"});
> let img = document.getElementById("myImage");
> img.onload = function() {
> let canvas = document.getElementById("myCanvas");
> let ctx = canvas.getContext("2d");
> ctx.drawImage(this, 0, 0);
> };
> img.src = URL.createObjectURL(blob);
> }
>
> Fourth, the performance is indeed substantially faster than my previous 
> approach based on using SetIndex 
> <https://golang.org/pkg/syscall/js/#Value.SetIndex> to write directly to 
> the canvas, even though the new approach requires the extra steps of 
> encoding the image in PNG format and copying the image data from an img 
> to a canvas.  The following performance data, measured with Go 1.14 and 
> Chromium 80.0.3987.132 on an Ubuntu Linux system, is averaged over 10 
> runs:
>
> *Old*: 686.9 ± 7.6 ms
> *New*: 290.4 ± 4.1 ms (284.3 ± 4.2 on the WebAssembly side plus 6.0 ± 2.3 
> on the JavaScript side)
>
> This is the time to render a simple 800×800 gradient pattern.
>
> I hope others find this useful.
>
> — Scott
>

-- 
You received this message because you are subscribed to the Google 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/c5e6ec50-c391-427b-8c00-01cf175e24d1n%40googlegroups.com.


[go-nuts] go.pkg.dev: blitznote.com/src/semver doesn't show up

2020-06-26 Thread Mark Kubacki
Hi,

I've noticed my package, blitznote.com/src/semver, doesn't show up in 
pkg.go.dev despite having been licensed under one of the blessed licenses, 
being some months old, and having been pulled several times using the 
default proxy.

Specifically, searching for “semver” won't produce it, even though after 
some pages search results are no longer original code (but forks, 
vendorings).

Going directly through 
https://pkg.go.dev/blitznote.com/src/semver/v3?tab=doc will work.

Where can I find the requirements for having it (and other modules of mine) 
included in search results?

Thanks, Mark

-- 
You received this message because you are subscribed to the Google 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/2faffdcd-3e5b-4f6d-a00a-55fc872d5296n%40googlegroups.com.


[go-nuts] [generics] tiny typo in Map/Reduce/Filter examples

2020-06-17 Thread Mark
At the end of this section where it shows the outputs:
```go

floats := slices.Map(s, func(i int) float64 { return float64(i) })// Now float2 
is []float64{1.0, 2.0, 3.0}.
```
shouldn't that be:
```go
floats := slices.Map(s, func(i int) float64 { return float64(i) })// Now floats 
is []float64{1.0, 2.0, 3.0}.
```

-- 
You received this message because you are subscribed to the Google 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/50d7ea44-9aa2-4688-84fd-22fb2c08f09ao%40googlegroups.com.


[go-nuts] Re: Client certificate not sent to server

2020-05-19 Thread Mark Petrovic
I know this is an old thread, but I found it, so others might, too.  

I struggled with a similar problem of the Go HTTP client not sending client 
certs when challenged by the server.  Yet, curl worked fine when given the 
same client certs, calling the same server endpoint.  The cert chains I was 
dealing with look like

leaf + intermediate + root


The solution for me was to provide the server (Envoy proxy) with a the root 
cert AND intermediate cert, the latter of which signed my Go client cert.  
When the server challenges the client for its cert, the server will send a 
TLS Certificate Request with, among other things, the certificate authority 
that must have signed the client cert.  Without including the intermediate 
cert with the root cert on the server side, the client cannot not build a 
complete path from its client cert to the root and therefore cannot 
determine which cert to send in response.  The client will not use 
tls.Config.RootCAs in this analysis (RootCAs is for validating the server 
cert chain).  Moreover, when the client parses its cert with 

cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)


only the leaf is returned even if the certFile contains the concatenated 
intermediate.

Including the full cert bundle on the server side solves this for me.

Hope that helps.



On Tuesday, March 17, 2015 at 10:19:01 AM UTC-7, Dots Connected wrote:
>
> Hello!
>
> I am trying to access an API served by nginx (with a self-signed SSL cert) 
> that requires client certificate authentication, and while I can 
> successfully auth with curl, I unable to accomplish the same with golang.
>
> Example using curl:
>
> # Will not work
> curl -k https://127.0.0.1/api
>
> # Works
> curl -k -E example_key+cert.pem https://127.0.0.1/api
>
>
> I found an example from this list that I've tried to adapt:
>
> https://groups.google.com/forum/#!topic/golang-nuts/dEfqPOSccIchttps://groups.google.com/forum/#!topic/golang-nuts/dEfqPOSccIc
>  
> 
> And another from github:
> https://gist.github.com/michaljemala/d6f4e01c4834bf47a9c4
>
> Despite this, golang gets the same result as the first curl with no client 
> cert.
> Am I missing something, or is this a regression in go?
>
> I'm on go version go1.4.2 linux/amd64. My code (or via 
> http://pastebin.com/LGiXZpgx):
>
> package main
>
> import (
> "crypto/tls"
> "io/ioutil"
> "log"
> "net/http"
> )
>
> func main() {
>
> certFile := "example_cert.pem"
> keyFile := "example_key.pem"
>
> // Load client cert
> cert, err := tls.LoadX509KeyPair(certFile, keyFile)
> if err != nil {
> log.Fatal(err)
> }
>
> // Setup HTTPS client
> tlsConfig := {
> Certificates: []tls.Certificate{cert},
> ClientAuth: tls.RequireAndVerifyClientCert,
> InsecureSkipVerify: true,
> }
> tlsConfig.BuildNameToCertificate()
>
> transport := {
> TLSClientConfig: tlsConfig,
> }
> client := {
> Transport: transport,
> }
>
> // Do GET something
> resp, err := client.Get("https://localhost/api/;)
> if err != nil {
> log.Fatal(err)
> }
> defer resp.Body.Close()
>
> // Dump response
> data, err := ioutil.ReadAll(resp.Body)
> if err != nil {
> log.Fatal(err)
> }
> log.Println(string(data))
> }
>
>

-- 
You received this message because you are subscribed to the Google 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/43ca36e6-bffe-4b2f-8ee6-c34288685023%40googlegroups.com.


[go-nuts] SWIG-generated Go wrapper mishandling(?) pointers to pointers to structs

2020-04-17 Thread mark mellar
(Cross posting with SO 
https://stackoverflow.com/questions/61258160/swig-generated-go-wrapper-mishandling-pointers-to-pointers-to-structs
)

Hi folks,

We're integrating a Go program with a 3rd party C api, but are getting some 
odd results when working with pointers to pointers to structs. A model of 
the header file looks a bit like this...

//mytest.h 

typedef struct Books {
 char title[50];
 char author[50];
 char subject[100];
 int book_id;
} 

Book; extern void initbook(Book** b);

With a model implementation like this...

//mytest.c 
#include  
#include  
#include  

typedef struct Books {
 char title[50];
 char author[50];
 char subject[100];
 int book_id; 
} Book; 

void initbook(Book** b){ *b = malloc(sizeof(Book));
 strcpy( (*b)->title, "A Book Title"); 
}

We've tried wrapping the API with a very simple SWIG file which looks like 
this...

%module mytest %{
 #include "./mytest.h" 
%} 
%include "./mytest.h"

And call it from a Go main function like this...

//main.go 

package main 
import "fmt" 
import "mytest" 
func main() {
 bookPtr := mytest.NewBook()
 mytest.Initbook(bookPtr)
 fmt.Printf("title: '%s'\n", bookPtr.GetTitle()) 
}

However, we've found when we run this we the value being returned from 
GetTitle() is garbled

> go run ../main.go 
title: '??'

Digging in to the generated C code we found that editing the Book 
constructor to return Book** rather than Book*, and then modifying the 
GetTitle function to receive a Book** instead of Book* things started 
working as expected.

Any hints on how we might configure SWIG to generate a version of the code 
which works for us. without us having to hack what it generates?

Thanks!

Mark

-- 
You received this message because you are subscribed to the Google 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/acc6b4f8-2928-4b07-91fa-5673396137e9%40googlegroups.com.


Re: [go-nuts] Cgo fixed length array woes

2020-01-29 Thread mark mellar
Thanks Ian!

My C's a bit rusty, I'd expected I'd have to explicitly allocate some 
memory for rLimits, similar to askedHosts, turns out that isn't required 
after all and your suggestion of setting element by element is working like 
a charm!

Thanks again,

Mark

On Tuesday, January 28, 2020 at 3:21:55 PM UTC, Ian Lance Taylor wrote:
>
> On Tue, Jan 28, 2020 at 4:44 AM mark mellar  > wrote: 
> > 
> > Hi Folks, I'm having some trouble instantiating a C struct from a 3rd 
> party API. 
> > 
> > I'm not sure if this is more a C question or a Go question, details in 
> the code below, any help would be much appreciated! 
> > 
> > M 
> > 
> > // This non-compiling example demonstrates an issue I'm having 
> integrating a 3rd party C api with my Go code 
> > // The comment preceding 'import "C"' constitutes C code which is 
> interpreted as a header when compiling. 
> > // 'api_struct' represents the 3rd party struct I'm attempting to 
> instantiate and populate in my Go Code 
> > //we cannot make changes to this struct 
> > // other c functions in the comment are helper functions I've written to 
> instantiate certain C types 
> > 
> > // The go code defines an array of strings and an array of ints. For 
> each of these arrays a helper 
> > // function is called to create a C array of the C equivalent type 
> before populating that array. 
> > // Once C arrays have been populated they are assigned to fields in the 
> a new api_struct. 
> > 
> > // This method works fine for the string array, but compile fails when 
> we get to the int array 
> > // This is because makeIntArray returns *_Ctype_int but 
> api_struct.rLimits expects [12]_Ctype_int. Here's the error... 
> > // cannot use cInts (type *_Ctype_int) as type [12]_Ctype_int in field 
> value 
> > 
> > // I'd like to modify makeIntArray to return a [12]_Ctype_int but I 
> can't seem to find the right syntax to achieve this 
> > package main 
> > 
> > /* 
> > #define  ARRLEN 12 
> > #include  
> > 
> > struct api_struct { 
> > char**askedHosts; 
> > int rLimits[ARRLEN]; 
> > }; 
> > 
> > static char**makeCharArray(int size) { 
> > return calloc(sizeof(char*), size); 
> > } 
> > 
> > static void setArrayString(char **a, char *s, int n) { 
> > a[n] = s; 
> > } 
> > 
> > static void freeCharArray(char **a, int size) { 
> > int i; 
> > for (i = 0; i < size; i++) 
> > free(a[i]); 
> > free(a); 
> > } 
> > 
> > static int*makeIntArray() { 
> > int* p = malloc(sizeof(p) * ARRLEN); 
> > return p; 
> > } 
> > 
> > static void setArrayInt(int *a, int s, int n) { 
> > a[n] = s; 
> > } 
> > 
> > static void freeIntArray(int *a, int size) { 
> > free(a); 
> > } 
> > 
> > 
> > */ 
> > import "C" 
> > import "fmt" 
> > 
> > func main() { 
> > goHosts := []string{"host1", "host2", "host3"} 
> > cHosts := C.makeCharArray(C.int(len(goHosts))) 
> > for i, s := range goHosts { 
> > C.setArrayString(cHosts, C.CString(s), C.int(i)) 
> > } 
> > 
> > goLimits := []int{1,2,3,4,5,6,7,8,9,10,11,12} 
> > cInts := C.makeIntArray() 
> > for i, s := range goLimits { 
> > C.setArrayInt(cInts, C.int(s), C.int(i)) 
> > } 
> > 
> > s := C.struct_api_struct{ 
> > askedHosts: cHosts, 
> > rLimits: cInts, 
> > } 
> > fmt.Printf("%+v\n", s) 
> > } 
>
>
> The easy, and likely more efficient, way is to just set the rLimits 
> field element by element. 
>
> There is no safe way to convert from a *C.int to a [12]C.int in Go. 
> You can do it easily enough using unsafe. 
>
> a := *(*[12]C.int)(unsafe.Pointer(p)) 
>
> This is of course only safe if p does in fact point to 12 C.int values. 
>
> 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/7470e567-a05d-4330-a095-24ef995126d0%40googlegroups.com.


Re: [go-nuts] JSON: Having trouble parsing map keys with dots like {"foo.bar":"baz"}

2020-01-29 Thread Mark Hansen
Ah, I see what's going on: Go is mapping the "qux" field to the Qux struct
arg just because they're case-insensitively equal. Go's totally ignoring my
invalid struct tag.

D'oh, I was totally holding it wrong. Thanks everyone! :-)

On Wed, 29 Jan 2020 at 08:12, Mark Hansen  wrote:

> Ah, thanks! Thought I might be holding it wrong.
>
> Still though, isn’t it strange that the extra space works if you don’t
> have the dot in the key?
>
>
>
> On Wed, 29 Jan 2020 at 00:59, Lutz Horn  wrote:
>
>> Remove the blank in ``json: "baz.bar"` and make it `json:"baz.bar"`. This
>> works: https://play.golang.com/p/i9SURYgGO66
>>
>> 
>> Von: golang-nuts@googlegroups.com  im
>> Auftrag von m...@markhansen.co.nz 
>> Gesendet: Dienstag, 28. Januar 2020 12:14
>> An: golang-nuts
>> Betreff: [go-nuts] JSON: Having trouble parsing map keys with dots like
>> {"foo.bar":"baz"}
>>
>> Hi folks, for background, I'm trying to read the Kaiterra API<
>> https://www.kaiterra.com/dev/#overview> using encoding/json, which has
>> JSON values like this:
>>
>>
>> {"id":"-0001-0001--7e57c0de","info.aqi":{"ts":"2018-03-26T08:53:20Z","data":{"pm10":120,"pm25":214}}}
>>
>> I'm having trouble parsing the "info.aqi" field using encoding/json. I
>> set the "info.aqi" field as a struct tag `json: "info.aqi"`, but the struct
>> is just empty after parsing.
>>
>> It seems more likely I'm holding it wrong, but I'm wondering if perhaps
>> this is a bug in Go's JSON parsing?
>>
>> I thought I'd make a minimal repro test, which fails:
>>
>> package main
>>
>> import (
>> "encoding/json"
>> "strings"
>> "testing"
>> )
>>
>> type Foo struct {
>> BazBar string `json: "baz.bar"`
>> Quxstring `json: "qux"`
>> }
>>
>> func TestDotKeyJsonParsing(t *testing.T) {
>> f := {}
>> d := json.NewDecoder(strings.NewReader(`{"baz.bar": "hello", "qux":
>> "hi"}`))
>> err := d.Decode(f)
>> if err != nil {
>> t.Fatalf("json decoding failed: %v", err)
>> }
>> if f.Qux != "hi" {
>> t.Fatalf("Expected f.Qux to be hi")
>> }
>>
>> if f.BazBar != "hello" {
>> t.Errorf("wanted: hello, got: %q", f.BazBar)
>> }
>> }
>>
>> And the Qux field passes fine, but the BazBar field is not set, so the
>> test fails there:
>> --- FAIL: TestDotKeyJsonParsing (0.00s)
>> /Users/mark/projects/godot/dot_test.go:26: wanted: hello, got: ""
>>
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to golang-nuts+unsubscr...@googlegroups.com> golang-nuts+unsubscr...@googlegroups.com>.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/golang-nuts/539f857c-d96a-45af-9a74-c328753bd12d%40googlegroups.com
>> <
>> https://groups.google.com/d/msgid/golang-nuts/539f857c-d96a-45af-9a74-c328753bd12d%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/CAM07o6TiccrXvLCTeDk%3DWS5akcBZ32LiFmDW95gfV4PAmgnLQQ%40mail.gmail.com.


Re: [go-nuts] JSON: Having trouble parsing map keys with dots like {"foo.bar":"baz"}

2020-01-28 Thread Mark Hansen
Ah, thanks! Thought I might be holding it wrong.

Still though, isn’t it strange that the extra space works if you don’t have
the dot in the key?



On Wed, 29 Jan 2020 at 00:59, Lutz Horn  wrote:

> Remove the blank in ``json: "baz.bar"` and make it `json:"baz.bar"`. This
> works: https://play.golang.com/p/i9SURYgGO66
>
> 
> Von: golang-nuts@googlegroups.com  im
> Auftrag von m...@markhansen.co.nz 
> Gesendet: Dienstag, 28. Januar 2020 12:14
> An: golang-nuts
> Betreff: [go-nuts] JSON: Having trouble parsing map keys with dots like
> {"foo.bar":"baz"}
>
> Hi folks, for background, I'm trying to read the Kaiterra API<
> https://www.kaiterra.com/dev/#overview> using encoding/json, which has
> JSON values like this:
>
>
> {"id":"-0001-0001--7e57c0de","info.aqi":{"ts":"2018-03-26T08:53:20Z","data":{"pm10":120,"pm25":214}}}
>
> I'm having trouble parsing the "info.aqi" field using encoding/json. I set
> the "info.aqi" field as a struct tag `json: "info.aqi"`, but the struct is
> just empty after parsing.
>
> It seems more likely I'm holding it wrong, but I'm wondering if perhaps
> this is a bug in Go's JSON parsing?
>
> I thought I'd make a minimal repro test, which fails:
>
> package main
>
> import (
> "encoding/json"
> "strings"
> "testing"
> )
>
> type Foo struct {
> BazBar string `json: "baz.bar"`
> Quxstring `json: "qux"`
> }
>
> func TestDotKeyJsonParsing(t *testing.T) {
> f := {}
> d := json.NewDecoder(strings.NewReader(`{"baz.bar": "hello", "qux":
> "hi"}`))
> err := d.Decode(f)
> if err != nil {
> t.Fatalf("json decoding failed: %v", err)
> }
> if f.Qux != "hi" {
> t.Fatalf("Expected f.Qux to be hi")
> }
>
> if f.BazBar != "hello" {
> t.Errorf("wanted: hello, got: %q", f.BazBar)
> }
> }
>
> And the Qux field passes fine, but the BazBar field is not set, so the
> test fails there:
> --- FAIL: TestDotKeyJsonParsing (0.00s)
> /Users/mark/projects/godot/dot_test.go:26: wanted: hello, got: ""
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com golang-nuts+unsubscr...@googlegroups.com>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/539f857c-d96a-45af-9a74-c328753bd12d%40googlegroups.com
> <
> https://groups.google.com/d/msgid/golang-nuts/539f857c-d96a-45af-9a74-c328753bd12d%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/CAM07o6SFwTWOqGZ_7mwqFFa03hqvdHB9HZePMGp2Xr1EbvA1mQ%40mail.gmail.com.


[go-nuts] JSON: Having trouble parsing map keys with dots like {"foo.bar":"baz"}

2020-01-28 Thread mark
Hi folks, for background, I'm trying to read the Kaiterra API 
<https://www.kaiterra.com/dev/#overview> using encoding/json, which has 
JSON values like this:

{"id":"-0001-0001--7e57c0de","*info.aqi*
":{"ts":"2018-03-26T08:53:20Z","data":{"pm10":120,"pm25":214}}}

I'm having trouble parsing the "info.aqi" field using encoding/json. I set 
the "info.aqi" field as a struct tag `json: "info.aqi"`, but the struct is 
just empty after parsing.

It seems more likely I'm holding it wrong, but I'm wondering if perhaps 
this is a bug in Go's JSON parsing?

I thought I'd make a minimal repro test, which fails:

package main

import (
"encoding/json"
"strings"
"testing"
)

type Foo struct {
BazBar string `json: "baz.bar"`
Quxstring `json: "qux"`
}

func TestDotKeyJsonParsing(t *testing.T) {
f := {}
d := json.NewDecoder(strings.NewReader(`{"baz.bar": "hello", "qux": "hi"}`))
err := d.Decode(f)
if err != nil {
t.Fatalf("json decoding failed: %v", err)
}
if f.Qux != "hi" {
t.Fatalf("Expected f.Qux to be hi")
}

if f.BazBar != "hello" {
t.Errorf("wanted: hello, got: %q", f.BazBar)
}
}

And the Qux field passes fine, but the BazBar field is not set, so the test 
fails there:
--- FAIL: TestDotKeyJsonParsing (0.00s)
/Users/mark/projects/godot/dot_test.go:26: wanted: hello, got: ""

-- 
You received this message because you are subscribed to the Google 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/539f857c-d96a-45af-9a74-c328753bd12d%40googlegroups.com.


[go-nuts] Cgo fixed length array woes

2020-01-28 Thread mark mellar
Hi Folks, I'm having some trouble instantiating a C struct from a 3rd party 
API.

I'm not sure if this is more a C question or a Go question, details in the 
code below, any help would be much appreciated!

M

// This non-compiling example demonstrates an issue I'm having integrating 
a 3rd party C api with my Go code
// The comment preceding 'import "C"' constitutes C code which is 
interpreted as a header when compiling.  
// 'api_struct' represents the 3rd party struct I'm attempting to 
instantiate and populate in my Go Code
//we cannot make changes to this struct 
// other c functions in the comment are helper functions I've written to 
instantiate certain C types

// The go code defines an array of strings and an array of ints. For each 
of these arrays a helper
// function is called to create a C array of the C equivalent type before 
populating that array.
// Once C arrays have been populated they are assigned to fields in the a 
new api_struct.

// This method works fine for the string array, but compile fails when we 
get to the int array
// This is because makeIntArray returns *_Ctype_int but api_struct.rLimits 
expects [12]_Ctype_int. Here's the error...
// cannot use cInts (type *_Ctype_int) as type [12]_Ctype_int in field value

// I'd like to modify makeIntArray to return a [12]_Ctype_int but I can't 
seem to find the right syntax to achieve this
package main

/*
#define  ARRLEN 12
#include 

struct api_struct {
char**askedHosts;
int rLimits[ARRLEN];
};

static char**makeCharArray(int size) {
return calloc(sizeof(char*), size);
}

static void setArrayString(char **a, char *s, int n) {
a[n] = s;
}

static void freeCharArray(char **a, int size) {
int i;
for (i = 0; i < size; i++)
free(a[i]);
free(a);
}

static int*makeIntArray() {
int* p = malloc(sizeof(p) * ARRLEN);
return p;
}

static void setArrayInt(int *a, int s, int n) {
a[n] = s;
}

static void freeIntArray(int *a, int size) {
free(a);
}


*/
import "C"
import "fmt"

func main() {
goHosts := []string{"host1", "host2", "host3"}
cHosts := C.makeCharArray(C.int(len(goHosts)))
for i, s := range goHosts {
C.setArrayString(cHosts, C.CString(s), C.int(i))
}

goLimits := []int{1,2,3,4,5,6,7,8,9,10,11,12}
cInts := C.makeIntArray()
for i, s := range goLimits {
C.setArrayInt(cInts, C.int(s), C.int(i))
}

s := C.struct_api_struct{
askedHosts: cHosts,
rLimits: cInts,
}
fmt.Printf("%+v\n", 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/7aeed9ae-2670-429d-a273-76adea4ef905%40googlegroups.com.


[go-nuts] InfluxData is hiring remote Go engineers

2019-09-26 Thread mark
InfluxData is the leading open source time series database, purpose built 
for
monitoring metrics and events. We are expanding our talented engineering
organization, and we are hiring for a lot of positions that primarily 
include
programming in Go.

I am personally one of Influx's first engineering hires from nearly five 
years
ago, and now our engineering department has grown to around 60 engineers. 
If I
can answer any questions about any of the below positions, please reach out 
to
me at my first name @influxdata.com.

All of the below positions are remote. We are currently hiring in the UK,
Germany, Italy, and the following US states: AZ, CA, CO, CT, GA, ID, IL, MA,
MN, NC, NJ, NY, OH, OR, TX, UT, VA, and WA.

Database Engineer, Query Engines (https://grnh.se/2b5fee851)

Engineers on this team build our open source query engine, Flux:
https://github.com/influxdata/flux

We are looking for people with experience building query processors, query
engines, query optimizers, or stream processing systems.

Principal Database Engineer (https://grnh.se/542136e21)
===
This is a senior position on the team that builds the core storage engine 
for
influxdb.

Senior Software Engineer, Telegraf (https://grnh.se/37a885101)
==
This is a senior position on the team building out the Telegraf agent for
collecting and reporting many metrics.

Telegraf (https://github.com/influxdata/telegraf) is a large open source
project that interfaces with a considerable number of external systems and
libraries. Engineers on this team very frequently interact with the OSS
community on GitHub.

Senior Kubernetes / Continuous Delivery Engineer (https://grnh.se/e15748de1)

We are looking for engineers with experience guiding engineering 
organizations
towards continuous delivery patterns, efficiently deploying software to
multiple Kubernetes clusters running in multiple cloud providers. We are 
always
looking to improve our CI/CD pipeline as well. If you have experience in 
this
domain and are opinionated, I would love to hear from you as this is the 
team I
am personally leading right now.

Senior Software Engineer, Backend (https://grnh.se/527323fe1)
=
This is a senior position on the team responsible for the backend APIs (both
REST and gRPC) of our cloud services.

Please see https://grnh.se/ygda3s for a full list of open positions, 
including
other engineering roles such as:
- Security Engineer
- Site Reliability Engineer
- Engineering, Ecommerce (using Elixir and JavaScript)
- User Interface Engineer (using TypeScript and React)

and some non-engineering roles too, such as customer success, marketing, and
technical writing.

If nothing above looks like the right fit, but you feel like you would be a
good fit for the company, feel free to apply to the Talent Community link:
https://grnh.se/7a623e4b1

-- 
You received this message because you are subscribed to the Google 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/a07913be-9ded-463f-840f-eb1624f2cd7d%40googlegroups.com.


[go-nuts] Tips for reproducing flaky Go tests

2019-08-15 Thread mark
I put together a blog post on reproducing flaky Go tests: 
https://www.influxdata.com/blog/reproducing-a-flaky-test-in-go/

This was the result of what I've learned spending many, many hours hunting 
down many unreliable tests.

I hope these tips can help you out next time you have a test that fails in 
CI but passes locally.

-- 
You received this message because you are subscribed to the Google 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/5ec4932c-ec83-4875-857d-8522fe7fdc68%40googlegroups.com.


Re: [go-nuts] I know you cannot kill a goroutine, but ...

2019-08-10 Thread Mark Baldridge
I think I can handle the deadly embrace problem. The locks distribute into
"slots" based upon inode%slotCount. Just information irrelevant to the
observation. At the moment, I use RWMutex to protect each lock table slot
since it was more like previous thoughts on this subject. However, I plan
to convert them to goroutines, and pass a structure with user information
(return channel included, as well as the lock request information).
Requesting a lock requires populating appropriate fields in the struct that
describe the request. Presently, the mutex will wait if someone has my
lock. The channel can queue the request in that case. The return result
will indicate success of failure. For a deadly embrace, a new request would
say, "return that user's lock request with a failure". Once back, it could
go through the channel select and see a "clean up and go away" quit signal,
if I really want that user session to exit. Or it could simply return and
discover the request failed, and the program could retry or handle its
error as it desires.
I think the infinite loop situation will need to save some information
about each backward branch or call so the object code can receive a break
point. If 1000 users are all using the same code, that might not be
desirable if it is just some special data case that a particular user has
encountered. It would be ugly to have 1000 users hit modified object code
if the special case did not apply to them. It is comparable to having them
all log out, at the same time, when they are geographically distributed
around the world, so you can bounce the database, which I have seen
occasionally in production. Not pretty. That will require some more
thought. Perhaps a way to automatically migrate things to another instance
of the database.

On Fri, Aug 9, 2019 at 12:03 PM Robert Engels  wrote:

> The standard method in nearly all languages including go is to close the
> connection from another routine. Alternatively you can use a
> timeout/deadline on every operation.
>
>
> On Aug 9, 2019, at 1:34 PM, reik...@gmail.com wrote:
>
> Background:
> UniVerse is a Pick model, multivalue database,
> https://groups.google.com/forum/#!forum/mvdbms for some general
> information.
> Multivalue databases permit more than one value in a column for a row.
> Since you do not know the size of the column with hundreds or thousands of
> values in the column-row, you do not know the size of the record. Access
> dictates linked lists to handle variability in record size. So, every row
> gets a unique primary key and stored in hash tables with an appropriately
> large number of hash buckets for the data - key / value pairs. With good
> hashing, I can often access a record in a single disk access. Group (hash
> table bucket) locking happens within the environment, while users request
> row locking. Each user in UniVerse is a separate O/S process. Locking
> activity occurs in shared memory, using assembly test-and-set kinds of
> instructions or host-specific semaphores.
>
> After retiring, I decided it would be a fun experiment to build a
> clean-room implementation of UniVerse. Go does not do interprocess
> communication at the rate that would match the shared memory semaphore
> activity in UniVerse. A natural match implements each user as a goroutine.
> UniVerse provides an extended BASIC language for accessing and manipulating
> table data that runs close to the engine. In a language you can do silly
> things like create an infinite loop. In a production environment of 1000s
> of users, you cannot simply bounce the environment because one user is
> eating a CPU. An admin function to dismiss or kill a goroutine would be
> ideal. Not possible in the current Go world.
>
> For an infinite loop to exist, you need to branch "backwards" or call a
> routine that calls you back with some possible indirection. (An equivalent
> in Go is "for {}" with no break. Here, you would not get back to the
> traditional mechanism of telling a goroutine to shut down where one of the
> channels for select is the shutdown indicator.)  There may be other
> examples I have yet to think of. When I "compile" BASIC, I can put checks
> into those two functions, call, and branch (to a lower address), without
> inducing too much overhead. an unimportant detail is that the BASIC
> compiles to a p-code run on a run machine, comparable to a JVM. I might
> even be able to find the PC, Program Counter or IA, Instruction Address,
> and insert some kind of trap instruction opcode, that would cause it to try
> the select statement and see the shutdown channel. But in the general case,
> this may be insufficient. I think a "context" timeout would interrupt a
> properly long-running program in a way that might be hard to restart if
> shutdown was not requested.
>
> As a database, there is also the possibility of deadly embrace. Killing
> one of the two (or more) goroutines in a deadly embrace would be useful.
> This normally occurs on poorly managed 

Re: [go-nuts] Standard library ETag/Last-Modified conditional request logic and best practices?

2019-08-06 Thread mark . mcdx
Thanks Devon!

So just to clarify our request flow is:

Client > CDN > Go Reverse Proxy > Origin

Our Go Reverse Proxy has historically been responsible for adding caching 
headers (e.g. Cache-Control and Surrogate-Control) when the origins have 
failed to do so (as a way to ensure things are cached appropriately).

It's unclear to me why you should be setting an etag header if you're a 
> proxy. 
>

That's why when it came to looking at setting serve stale defaults for our 
origins (e.g. stale-while-revalidate and stale-if-error) I realized that 
somewhere along the chain an appropriate ETag/Last-Modified should be set 
and that's why I started wondering if our proxy should be responsible for 
setting them.

Even then I felt like setting Last-Modified was way outside the 
responsibility of our proxy, but that maybe setting of ETag would have 
sufficed.

Unless you're serving from the filesystem handler (which does 
> implement IMS/INM), you'll need to implement these yourself. 
>

I think your other related answers might explain to me why the go reverse 
proxy doesn't support conditional requests, in that it's NOT a 'caching 
proxy' and so being able to handle that revalidation logic wouldn't make 
sense.
 

> Note that you _could_ simply proxy this to the origin and let it 
> handle the validation. This is often overkill for what people actually 
> need, but it is guaranteed to work. 
>

OK, so as we are indeed just proxying the request pretty much 'as is' to 
the origin, i.e. the CDN is making the revalidation conditional request 
when our stale-while-revalidate TTL expires, I'm guessing (I appreciate 
this is the 'basics' of how a proxy works, but I want to talk it through in 
case I'm mistaken in any way!) the go proxy will transparently keep that 
information for the origin to respond with the appropriate 
ETag/Last-Modified, and the go proxy again will transparently pass back 
their response through to the CDN to then update its cache if it indeed got 
a `200 OK` from origin or to continue serving stale if the origin returned 
a `304 Not Modified` (and in either case I expect the origin should send 
ETag/Last-Modified headers regardless of 200/304 status').

A hash function over the body of the response would constitute strong 
> validation. I'm not sure why you'd need to mix in the path; there's 
> nothing wrong with serving the exact same content between two 
> endpoints, and the ETag is tied to a response object. 
>

Ah ok, so I was thinking along these lines, but was getting confused 
between content that is cached vs content that is rendered at 'runtime' 
(e.g. I was getting confused with the response containing a 

[go-nuts] Standard library ETag/Last-Modified conditional request logic and best practices?

2019-08-06 Thread mark . mcdx
Hello,

I'm using Go's standard library reverse proxy and I'm trying to figure out 
if the standard library HTTP web server (e.g. http.ListenAndServe) 
implements the relevant conditional request handling logic for 
ETag/Last-Modified headers.

I did some Googling and noticed the HTTP file system request handler 
(https://golang.org/src/net/http/fs.go) does implement that logic, but I 
couldn't find the same for the HTTP web server.

I also couldn't find any examples of setting ETags/Last-Modified (other 
than this basic implementation for setting ETags: 
https://github.com/go-http-utils/etag/blob/master/etag.go).

What's confusing me there is the concept of "strong" and "weak" validation 
and how certain scenarios might influence whether an ETag is marked as 
either strong or weak (depending on the implementation -- see 
https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests#Validators).

So to recap, my questions are (and I appreciate some of these are outside 
the scope of just Go -- so apologies if that's not allowed in this forum):

1. Should I set ETag/Last-Modified in a proxy? Last-Modified feels like 
it's not the responsibility of the proxy but the origin, where as an ETag 
is something I feel is "ok" to do in the proxy as a 'fallback' (as we 
already set 'serve stale' caching headers on behalf of our origins if they 
neglect to include them).

2. Do I need to implement `If-None-Match` and `If-Modified-Since` 
behaviours myself (i.e. is it not provided by the Go standard library's 
HTTP web server)?

3. I was planning on setting an ETag header on the response from within 
httputil.ReverseProxy#ModifyResponse but wasn't sure if that would be the 
correct place to set it.

4. What constitutes a strong/weak validator (e.g. would a simple hash 
function generating a digest of the URL path + response body suffice)?

Thanks for any help/insights/opinions y'all can share with me.

Kind regards,
Mark

-- 
You received this message because you are subscribed to the Google 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/b9428dbf-55d7-4ae2-ab11-523f94102071%40googlegroups.com.


[go-nuts] Reflection: How to retrieve index of map

2019-07-01 Thread Mark Bauermeister
I have the following code, where the TokenMap struct is actually part of 
another package. 
idMap is not exported and thus not accessible without reflection.

Through reflection I can easily find the value of "int", which is "28".
Now, I'd like to do the opposite though. I'd like to find "28"'s index (i e 
"int").

How would I go about that?

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

-- 
You received this message because you are subscribed to the Google 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/844522f8-145c-44c1-b382-338c2936d5fb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: [ANN] Gio: portable immediate mode GUI programs in Go for iOS/tvOS, Android, macOS, Linux, Windows

2019-06-14 Thread Mark Bauermeister
Any plans for a Vulkan back-end?

-- 
You received this message because you are subscribed to the Google 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/4472458b-51a1-4bed-9b70-794e7285000a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] make an empty slice

2019-06-06 Thread Mark Bauermeister
You mean a slice that is not of type Exam?

test []int

Should work.
Your slice does need to adhere to some type.

-- 
You received this message because you are subscribed to the Google 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/fba31d31-7797-45b0-9473-1b1ba88ad937%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Memory allocation question

2019-06-06 Thread Mark Bauermeister
Sorry in advance for the somewhat messy code, but this is something I've 
been trying to understand all day and can't quite come up with an 
explanation for.
Basically, I wrote the below code to experiment with different data types 
and their impact on performance and memory efficiency.

The code itself creates a map, an array, an empty slice and a slice already 
preallocated with the 1,000,000 required integers.

Each data type is being filled with numbers ranging from 0 to 999,999, then 
I output the execution time ("latency") and the memory usage ("Heap" and 
"Stack").

Now here is what I don't quite understand: Why would an array occupy more 
space on the heap and stack than a slice?

Is there an issue in my code or the way I measure heap/stack allocation?



[image: experiment.png] 
























package main

import (
"fmt"
"sync"
"time"

"runtime"

"github.com/fatih/color"
)

var mu sync.Mutex
var mem runtime.MemStats

func main() {
imap()
iarray()
ipreSlice()
islice()
}

func _green(text string) {
fmt.Fprintf(color.Output, color.GreenString(text))
fmt.Println()
}

func imap() {
_green("Map Implementation")
cache := make(map[int]int, 100)
start := time.Now()

for i := 0; i < 100; i++ {
mu.Lock()
cache[i] = i
mu.Unlock()
}
end := time.Since(start)
fmt.Printf("Latency: %v \n", end)

var sum int64
for _, v := range cache {
sum += int64(v)
}

fmt.Printf("Checksum: %v \n", sum)
printHeap()
printStack()
}

func iarray() {
_green("Array Implementation")
cache := [100]int{}
start := time.Now()

for i := 0; i < 100; i++ {
mu.Lock()
cache[i] = i
mu.Unlock()
}
end := time.Since(start)
fmt.Printf("Latency: %v \n", end)

var sum int64
for _, v := range cache {
sum += int64(v)
}

fmt.Printf("Checksum: %v \n", sum)
printHeap()
printStack()
}

func ipreSlice() {
_green("Preallocated Slice Implementation")
cache := make([]int, 100)
start := time.Now()

for i := 0; i < 100; i++ {
mu.Lock()
cache[i] = i
mu.Unlock()
}
end := time.Since(start)
fmt.Printf("Latency: %v \n", end)

var sum int64
for _, v := range cache {
sum += int64(v)
}

fmt.Printf("Checksum: %v \n", sum)
printHeap()
printStack()
}

func islice() {
_green("Slice Implementation")
cache := []int{}
start := time.Now()

for i := 0; i < 100; i++ {
mu.Lock()
cache = append(cache, i)
mu.Unlock()
}
end := time.Since(start)
fmt.Printf("Latency: %v \n", end)

var sum int64
for _, v := range cache {
sum += int64(v)
}

fmt.Printf("Checksum: %v \n", sum)
printHeap()
printStack()
}

func printHeap() {
runtime.ReadMemStats()
fmt.Printf("Heap: %v MB", float64(mem.HeapInuse)/1024/1024)
fmt.Println()
}

func printStack() {
runtime.ReadMemStats()
fmt.Printf("Stack: %v MB", float64(mem.StackInuse)/1024/1024)
fmt.Println()
fmt.Println()
}

-- 
You received this message because you are subscribed to the Google 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/07bc3bd3-8c9d-48d9-8a36-7e9e42d79637%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: Write to bufio Scanner from outside os.Stdin

2019-05-29 Thread Mark Bauermeister
Thanks!

I've changed the code to this:

var console *bufio.ReadWriter
var cmd string

func (g *Game) Parse() {
// reader should be wrapped inside an _input() function.

for {
console = bufio.NewReadWriter(
bufio.NewReader(os.Stdin),
bufio.NewWriter(os.Stdout))
fmt.Print(">>> ")

cmd, _ = console.ReadString('\n')
switch cmd {
...
...

Now my thinking is that I should be able to simply assign "cmd" from 
anywhere outside the loop
followed by a newline character (i e "cmd = "Test \n") and the reader 
should pick it up as if it was a manual input.

Unfortunately, that doesn't quite seem to work yet.

On Wednesday, 29 May 2019 19:26:58 UTC+2, Mark Bauermeister wrote:
>
> I'm in the process of writing a text adventure parser.
> By default, the parser simply uses Stdin.
>
> i e 
>
> for {
> fmt.Print(">>> ")
>
> reader := bufio.NewScanner(os.Stdin)
> for reader.Scan() {
> switch reader.Text() {
> ...
> ...
>
> This is quite convenient. However, I now want to be able to pass in text 
> from outside this for-loop. Say I have a function "Invoke(arg string)" 
> which I should be able to call to pass
> arguments straight to the Scanner interface.
>
> What would be the most straightforward way to achieve this?
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/1ad89796-0624-47ad-9fdf-ad6c4786c025%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Write to bufio Scanner from outside os.Stdin

2019-05-29 Thread Mark Bauermeister
I'm in the process of writing a text adventure parser.
By default, the parser simply uses Stdin.

i e 

for {
fmt.Print(">>> ")

reader := bufio.NewScanner(os.Stdin)
for reader.Scan() {
switch reader.Text() {
...
...

This is quite convenient. However, I now want to be able to pass in text 
from outside this for-loop. Say I have a function "Invoke(arg string)" 
which I should be able to call to pass
arguments straight to the Scanner interface.

What would be the most straightforward way to achieve this?

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/b34d4bea-d819-4832-9ebd-db11709d6b0c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Re: Any alternative to go-bindata that supports dynamic assets?

2019-05-26 Thread Mark Bauermeister
Actually.

To answer my own question, this probably suffices for most/all of my use 
cases.

func LoadScript(script string) {
L := lua.NewState()
defer L.Close()

file, err := Asset(script)

if err = L.DoFile(script); err != nil {
L.DoString(string(file))
}
}

On Sunday, 26 May 2019 15:44:01 UTC+2, Mark Bauermeister wrote:
>
> My use case is a game engine that uses Lua scripts.
> Naturally, Lua scripts can be changed during runtime without rebuilding 
> the entire project.
>
> Since go-bindata doesn't actually load the file during runtime but merely 
> precompiles it to a string representation, it doesn't work for dynamic 
> content and one of the main benefits
> of using a dynamic scripting language is lost in the process.
>
> Is there any alternative that would allow loading the files dynamically 
> during development and baking them into the source upon release?
> Or am I better off just writing some custom logic that simply tries to 
> load the file from the file system and, upon failing, reverts to the baked 
> data?
>

-- 
You received this message because you are subscribed to the Google 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/9305b5d0-0f62-430d-9549-e96cc22f69af%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Any alternative to go-bindata that supports dynamic assets?

2019-05-26 Thread Mark Bauermeister
My use case is a game engine that uses Lua scripts.
Naturally, Lua scripts can be changed during runtime without rebuilding the 
entire project.

Since go-bindata doesn't actually load the file during runtime but merely 
precompiles it to a string representation, it doesn't work for dynamic 
content and one of the main benefits
of using a dynamic scripting language is lost in the process.

Is there any alternative that would allow loading the files dynamically 
during development and baking them into the source upon release?
Or am I better off just writing some custom logic that simply tries to load 
the file from the file system and, upon failing, reverts to the baked data?

-- 
You received this message because you are subscribed to the Google 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/4d73c613-fc57-4316-82c8-8e1531b4290f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Go-SQLite3: Convert between string and slice

2019-05-05 Thread Mark Bauermeister
type Country struct {
ID   int`json:"id"`
States string `json:"states"`
}
var Countries []Country
func getAllCountries() {
rows, err := db.Query("select id, states from countries")
if err != nil {
astilog.Error(err)
}
defer rows.Close()
for rows.Next() {
var id int
var states string
err := rows.Scan(, )
if err != nil {
astilog.Error(err)
}
Countries = append(Countries, Country{id, states})
}
}


See (fictional) code above.

This is something I've been struggling with for a while.

In the past, I'd simply accept the string representation of a JSON array 
and operate on that directly.
However, that's less flexible and certainly less elegant.

What's the correct way of turning the above code into something a bit more 
canonical?
Since SQLite doesn't know of arrays, I obviously need to somehow cast the 
array to a string representation somewhere before "rows.Scan". Which is the 
part I'm struggling with.

The data presentation I'm hoping for looks as follows:

type Country struct {
ID   int `json:"id"`
States []State `json:"states"`
}

type State struct {
Shortstring  `json:"short"`
Population int `json:"population"`
}

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


[go-nuts] Extend map with another map

2019-05-03 Thread Mark Bauermeister
I'm in the process of writing my own Text Adventure/Interactive Fiction 
engine/library and am now running into a bit of a problem attempting to 
extend the parser.

On the implementation side (i e a game), this is how a game is initially 
set up.
game = mid.Game{
Title:  "Cloak of Darkness",
Author: "Roger Firth (implemented by Mark Bauermeister)",
Intro: `Hurrying through the rainswept November night, you're glad 
to see the
bright lights of the Opera House.

It's surprising that there aren't more
people about but, hey, what do you expect in a cheap demo game...?`,
Goodbye:  "See you later!",
MaxScore: 2,
Verbs: map[string]func(...string){
"drop": drop,
},
Synonyms: map[string][]string{
"drop": {"throw"},
},
}

Now on the engine/library side, standard verbs are currently hardcoded 
inside the parser loop.
Ideally, I'd like to add them to the same "Verbs" map though.

Is there a straightforward way to include the contents of one map in 
another?

Ideally, I'd like to have a "BuiltinVerbs" map and include it as such:

Verbs: map[string]func(...string){
BuiltinVerbs,
"drop": drop,
},

The parser currently looks like this and "g.Verbs" should eventually 
contain both, the game designer's chosen verbs and (if so chosen) the 
built-in verbs:

func (g *Game) Parse() {
reader := bufio.NewScanner(os.Stdin)
for {
fmt.Print(">>> ")
for reader.Scan() {
switch reader.Text() {
case "quit":
if len(g.Goodbye) != 0 {
fmt.Println(g.Goodbye)
} else {
fmt.Println("Goodbye!")
}
os.Exit(0)
default:
for n, c := range g.Verbs {
s := g._synonymize(reader.Text())
switch s {
case n:
c()
default:
fmt.Println("I beg your pardon?")
}
}
}
fmt.Print(">>> ")
}
}
}

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


[go-nuts] Re: Gomobile Reverse Bindings: Cannot import any android packages

2019-04-25 Thread Mark Bauermeister
Ok. I fixed it.

For anybody interested, here's how I solved it.

On the Go side, I extended my exported function by adding "ctx 
content.Context" as a parameter (i e "func Hello(ctx content.Context).
On the Java side, I'm then passing the mobile context as follows (this is a 
React Native app, so it's bound to different from regular Android apps):

Context ctx = getReactApplicationContext();
Mobile.hello(ctx);


I can then access the application context from the Go side.

Now one thing that would be interesting still is whether/how I can reverse 
bind "com.facebook.react.bridge.ReactContextBaseJavaModule" on the Go side 
directly,
so I can call "getReactApplicationContext()" directly from the Go side 
rather than pass the context in from Java.

I know there's "-classpath" but how does it actually work for external Java 
libraries?

On Wednesday, 24 April 2019 15:27:31 UTC+2, Mark Bauermeister wrote:
>
> Yea. Turns out that was indeed the issue. I tried accessing a method that 
> didn't actually exist.
>
> Unfortunately, your code doesn't work either. It leads to a segmentation 
> violation/nil pointer error.
> I suspect one needs to somehow get the right context from the Java side. 
> Question is how.
>
> I already tried an OnCreate override func, but that one is somehow never 
> called.
>
> On Wednesday, 24 April 2019 15:08:02 UTC+2, ma...@eliasnaur.com wrote:
>>
>>
>>
>> On Wednesday, April 24, 2019 at 2:34:34 PM UTC+2, Mark Bauermeister wrote:
>>>
>>> I'm currently experimenting with Gomobile Reverse Bindings (my hope is 
>>> to eventually be able to call getFilesDir(), so I can save my SQLite3 DB on 
>>> mobile) and it is, quite literally, driving me insane.
>>> I've followed the sparse information available, was able to successfully 
>>> work with 'import "Java/java/lang/System" and call 
>>> "System.currentTimeMillis()".
>>>
>>> Now I'm trying to import "Java/android/content" and it fails outright, 
>>> stating that the package "Java/android/content" cannot be found.
>>>
>>> What is the correct import path for Android packages, or is there 
>>> something else I need to do that I'm missing?
>>>
>>
>> Note that reverse binding packages will only be generated if you use a 
>> type from it; importing is unfortunately not enough.
>>
>> Perhaps
>>
>> import "Java/android/content"
>>
>> var ctx content.Context
>> ctx.GetFilesDir()
>>
>> is enough to get further.
>>
>> The reverse bindings are very fickle, sorry.
>>
>>  - elias
>>
>

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


Re: [go-nuts] Go if else syntax .. suggested replacement

2019-04-25 Thread Mark Volkmann
There are many counter-examples. What is the likelihood that someone who is
not familiar with the "?" operator will be familiar with the operators for
getting (*) and dereferencing (&) a pointer. And what is "<-"? Certainly
people not familiar with Go will initially be confused by operators related
to channels.

If you allow people to use pointers, will they use pointers to pointers to
pointers to pointers?

On Thu, Apr 25, 2019 at 9:19 AM Sam Whited  wrote:

> On Wed, Apr 24, 2019, at 14:08, Mark Volkmann wrote:
> > Are there really developers that find this unreadable?
> >
> > color := temperature > 80 ? “red” : “green”
>
> Yes.
>
> What is "?"? If I've never seen that before I have no easy way to search
> for that, and a random symbol me nothing about what it does. Go
> specifically tries to stick to keywords because even if you've never
> seen them before it's generally easier to figure out what they do (or to
> search for them if you're not sure).
>
> Not to mention that even if you do know what they do, that specific
> statement isn't the problem. If you allow people to do that, they'll end
> up trying to nest it 5 levels deep. Go tries not to give people the
> tools to shoot themselves in the foot for some tiny perceived advantage.
>
> —Sam
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


Re: [go-nuts] Go if else syntax .. suggested replacement

2019-04-24 Thread Mark Volkmann
Nested ternaries are fairly readable in JavaScript these days due to the
use of Prettier for code formatting.
gofmt could do the same.
For example, this:

lc_unicodeliterals = quote=='u' ? 1 : quote=='U' ? 0 : !!(ast.locale.set &
AST_LC_unicodeliterals);

could be formatted to this:

lc_unicodeliterals =
  quote == 'u' ? 1 :
  quote == 'U' ? 0 :
  !!(ast.locale.set & AST_LC_unicodeliterals);

On Wed, Apr 24, 2019 at 4:02 PM Kurtis Rader  wrote:

> On Wed, Apr 24, 2019 at 1:14 PM andrey mirtchovski 
> wrote:
>
>> Here's the lore associated with the subject: Ken wanted ternary, Rob
>> and Robert did not. They overruled Ken (remember, early on all three
>> had to agree for a feature to go in). The end.
>>
>> The number of frivolous and egregious abuse of ternary that I've seen
>> in _modern_ C code is too high.jpg
>>
>
> +100 to that sentiment. While the brevity of a ternary expression
> is  useful for trivial cases it tends to be abused. For your
> amusement/horror here are just a few, of a couple hundred, examples of
> ternary being abused in the AT AST (which includes ksh) source:
>
>
> https://github.com/att/ast/blob/e770c77e9816e156c6df4a455e71b5f9fff79310/src/cmd/ksh93/edit/hexpand.c#L447
>
>
> https://github.com/att/ast/blob/e770c77e9816e156c6df4a455e71b5f9fff79310/src/cmd/ksh93/sh/string.c#L344-L346
>
>
> https://github.com/att/ast/blob/8504cd407846d192881a94d507333697f016a85a/src/lib/libast/include/sfio.h#L359-L360
>
>
> https://github.com/att/ast/blob/8504cd407846d192881a94d507333697f016a85a/src/lib/libast/include/cdt.h#L313-L316
>
>
> https://github.com/att/ast/blob/e770c77e9816e156c6df4a455e71b5f9fff79310/src/lib/libz/deflate.c#L597-L609
>
> For those who don't want to follow those links this is the code from the
> first URL above:
>
> lc_unicodeliterals = quote=='u' ? 1 : quote=='U' ? 0 : !!(ast.locale.set &
> AST_LC_unicodeliterals);
>
> --
> Kurtis Rader
> Caretaker of the exceptional canines Junior and Hank
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


Re: [go-nuts] Go if else syntax .. suggested replacement

2019-04-24 Thread Mark Volkmann
I'm at a loss as to how that could be considered more readable that a
single ternary.
You've successfully changed five lines to four lines, but that's still a
long way from one line.

On Wed, Apr 24, 2019 at 12:15 PM Marcus Low  wrote:

> Yeah of course I was joking... the solution I provided does work for the
> "I need a one-liner" mentality, though.
>
> I believe this following solution fits your use case, and is simpler to
> read too:
>
> datalen := removedKeyken // removedKeyken must have been int32 in your
> example.
> if value != nil {
>datalen = len(value)
> }
>
>
>
> On Thu, Apr 25, 2019 at 1:05 AM Robert Engels 
> wrote:
>
>> I’m pretty sure you’re joking... but I think most are referring to simple
>> usages, like this (from my own code). Clearly, there are others was of
>> designing it to avoid the usage, but sometimes what is simple really is
>> simpler.
>>
>> var datalen int32
>> if value == nil {
>>datalen = removedKeyken
>> } else {
>>datalen = len(value)
>> }
>>
>>
>>
>> On Apr 24, 2019, at 11:31 AM, Marcus Low  wrote:
>>
>> I personally do not find ternary operators to be readable in any form.
>> For those who are truly desperate for that cosmetic one-line kick,
>> though, here's an example you can use (which looks just about as unreadable
>> as any ternary operator out there):
>>
>> // ternary returns 12345 if x is positive (x > 0).
>> // It returns -1 otherwise.
>> func ternary(x int) int {
>> return map[bool]int{true:12345,false:-1}[x>0]
>> }
>>
>>
>>
>> On Thursday, April 25, 2019 at 12:20:35 AM UTC+8, Robert Engels wrote:
>>>
>>> Yes, but the FAQ has similar concerns about readability and
>>> maintainability as reasons for not having generics, but adds the language
>>> “may change”... not sure that is consistent with the views on the tenant
>>> operator.
>>>
>>> > On Apr 24, 2019, at 9:52 AM, Ian Lance Taylor 
>>> wrote:
>>> >
>>> > The lack of the ?: operator in Go is a FAQ:
>>> > https://golang.org/doc/faq#Does_Go_have_a_ternary_form .
>>> >
>>> > Ian
>>>
>>> --
>> You received this message because you are subscribed to the Google Groups
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to golang-nuts+unsubscr...@googlegroups.com.
>> For more options, visit https://groups.google.com/d/optout.
>>
>> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


Re: [go-nuts] Go if else syntax .. suggested replacement

2019-04-24 Thread Mark Volkmann
Are there really developers that find this unreadable?

color := temperature > 80 ? “red” : “green”

I know what you are going to say. People will nest them. But even nested usage 
can be readable when formatted nicely with one condition per line. Another 
alternative is to allow only unnested ternaries. 

R. Mark Volkmann
Object Computing, Inc.

> On Apr 24, 2019, at 8:58 AM, Jan Mercl <0xj...@gmail.com> wrote:
> 
>> On Wed, Apr 24, 2019 at 3:48 PM L Godioleskky  wrote:
>> 
>> The lack of a Go ternary operator is at odds with Go's major theme of clean 
>> and easy to read syntax. Those who choose not to use the ternary operator 
>> can always resort back to Go's current 'if -else' or 'case' syntax. So Go 
>> syntax suffers no negative impact by adding the ternary op to its syntax 
>> list.  Those opposed to the ternary op should not be allowed to deny it use 
>> other Go programmers, that consider it useful.
> 
> That's backwards. Those who has to read the code can no more chose not
> to decrypt the unreadable 4-level nested ternary operations instead of
> 5 if statements.
> 
> And to follow on your "logic". If you add to Go even just 10% of what
> people consider useful, it will become a new C++, only much worse. And
> again by your very logic. Why we, that haven't chosen to code in C++
> in the first place, would be denied by others to use Go, when those
> others have C++ already at hand?
> 
> Let everyone use the language he/she likes. Why ruin it for others
> instead of that by forcing Go to become the same as his/her other
> favorite language?

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


[go-nuts] Re: Gomobile Reverse Bindings: Cannot import any android packages

2019-04-24 Thread Mark Bauermeister
Yea. Turns out that was indeed the issue. I tried accessing a method that 
didn't actually exist.

Unfortunately, your code doesn't work either. It leads to a segmentation 
violation/nil pointer error.
I suspect one needs to somehow get the right context from the Java side. 
Question is how.

I already tried an OnCreate override func, but that one is somehow never 
called.

On Wednesday, 24 April 2019 15:08:02 UTC+2, ma...@eliasnaur.com wrote:
>
>
>
> On Wednesday, April 24, 2019 at 2:34:34 PM UTC+2, Mark Bauermeister wrote:
>>
>> I'm currently experimenting with Gomobile Reverse Bindings (my hope is to 
>> eventually be able to call getFilesDir(), so I can save my SQLite3 DB on 
>> mobile) and it is, quite literally, driving me insane.
>> I've followed the sparse information available, was able to successfully 
>> work with 'import "Java/java/lang/System" and call 
>> "System.currentTimeMillis()".
>>
>> Now I'm trying to import "Java/android/content" and it fails outright, 
>> stating that the package "Java/android/content" cannot be found.
>>
>> What is the correct import path for Android packages, or is there 
>> something else I need to do that I'm missing?
>>
>
> Note that reverse binding packages will only be generated if you use a 
> type from it; importing is unfortunately not enough.
>
> Perhaps
>
> import "Java/android/content"
>
> var ctx content.Context
> ctx.GetFilesDir()
>
> is enough to get further.
>
> The reverse bindings are very fickle, sorry.
>
>  - elias
>

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


[go-nuts] Gomobile Reverse Bindings: Cannot import any android packages

2019-04-24 Thread Mark Bauermeister
I'm currently experimenting with Gomobile Reverse Bindings (my hope is to 
eventually be able to call getFilesDir(), so I can save my SQLite3 DB on 
mobile) and it is, quite literally, driving me insane.
I've followed the sparse information available, was able to successfully 
work with 'import "Java/java/lang/System" and call 
"System.currentTimeMillis()".

Now I'm trying to import "Java/android/content" and it fails outright, 
stating that the package "Java/android/content" cannot be found.

What is the correct import path for Android packages, or is there something 
else I need to do that I'm missing?

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


Re: [go-nuts] Go if else syntax .. suggested replacement

2019-04-24 Thread Mark Volkmann


> On Apr 24, 2019, at 6:22 AM, Robert Engels  wrote:
> 
> Though to the ops point, not sure why Go doesn’t have the ternary operator - 
> which is pretty ubiquitous. 

The idea of adding the ternary operator to Go has been debated many times. It’s 
clear that those in charge have a strong dislike for it. For me the lack of the 
ternary operator is one of main things I dislike about Go. It’s nails on a 
chalkboard for me to write a five line “if” statement when it could have been a 
one line assignment statement.

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


Re: [go-nuts] When to use panic?

2019-01-03 Thread Mark Volkmann
Typically explicit panics should only be used when an error occurs that
callers are not expected to handle. For expected errors, functions should
return an extra error return value, that callers can check.

On Thu, Jan 3, 2019 at 8:24 AM 伊藤和也  wrote:

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


-- 
R. Mark Volkmann
Object Computing, Inc.

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


Re: [go-nuts] reflect Kind method

2018-12-24 Thread Mark Volkmann
Maybe it would be good to add an indication of just the basic type of each type 
in the index. For example, is the type a struct, interface, or something else?

---
R. Mark Volkmann
Object Computing, Inc.

> On Dec 24, 2018, at 12:35 PM, Ian Lance Taylor  wrote:
> 
> On Mon, Dec 24, 2018 at 10:24 AM Mark Volkmann
>  wrote:
>> 
>> I guess my question boils down to what should be displayed in the index 
>> section under a type. Currently it seems the answer is ...
>> If the type is a struct or interface, list all the package functions that 
>> return that type.
>> If the type is a struct, list all its methods.
>> If the type is a struct, do not list its fields.
>> If the type is an interface, do not list its methods.
>> 
>> I wonder if those two "do not" lines are really desirable.
>> 
>> The other issue is that you can't tell from the index section whether 
>> something is a struct or interface. You have to click on it to find out.
> 
> The entries in the index section should link to something.  The index
> section isn't in itself a complete summary of the package or the names
> it contains.  If we list the methods of an interface, it will link to
> the definition of the interface.  If we list the fields of a struct,
> it will link to the definition of the struct.  That doesn't seem
> helpful.
> 
> Ian
> 
> 
>>> On Mon, Dec 24, 2018 at 12:04 PM Ian Lance Taylor  wrote:
>>> 
>>>> On Mon, Dec 24, 2018 at 9:29 AM Mark Volkmann  
>>>> wrote:
>>>> 
>>>> IIUC, Kind is a method of both Type and Value. But the index near the top 
>>>> of https://golang.org/pkg/reflect/ only shows it as a method of Value. If 
>>>> you click on "type Type" in the index, it scrolls to the description of 
>>>> that interface which includes the Kind method.
>>>> 
>>>> Is it wrong that the index excludes the Kind method in the list of Type 
>>>> methods?
>>> 
>>> It is displayed that way because Value is a struct while Type is an 
>>> interface.
>>> 
>>> Ian
>> 
>> 
>> 
>> --
>> R. Mark Volkmann
>> Object Computing, Inc.

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


Re: [go-nuts] reflect Kind method

2018-12-24 Thread Mark Volkmann
I guess my question boils down to what should be displayed in the index
section under a type. Currently it seems the answer is ...
If the type is a struct or interface, list all the package functions that
return that type.
If the type is a struct, list all its methods.
If the type is a struct, do not list its fields.
If the type is an interface, do not list its methods.

I wonder if those two "do not" lines are really desirable.

The other issue is that you can't tell from the index section whether
something is a struct or interface. You have to click on it to find out.

On Mon, Dec 24, 2018 at 12:04 PM Ian Lance Taylor  wrote:

> On Mon, Dec 24, 2018 at 9:29 AM Mark Volkmann 
> wrote:
> >
> > IIUC, Kind is a method of both Type and Value. But the index near the
> top of https://golang.org/pkg/reflect/ only shows it as a method of
> Value. If you click on "type Type" in the index, it scrolls to the
> description of that interface which includes the Kind method.
> >
> > Is it wrong that the index excludes the Kind method in the list of Type
> methods?
>
> It is displayed that way because Value is a struct while Type is an
> interface.
>
> Ian
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


[go-nuts] reflect Kind method

2018-12-24 Thread Mark Volkmann
IIUC, Kind is a method of both Type and Value. But the index near the top
of https://golang.org/pkg/reflect/ only shows it as a method of Value. If
you click on "type Type" in the index, it scrolls to the description of
that interface which includes the Kind method.

Is it wrong that the index excludes the Kind method in the list of Type
methods?

-- 
R. Mark Volkmann
Object Computing, Inc.

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


Re: [go-nuts] Re: if/switch statements as expressions

2018-12-21 Thread Mark Volkmann
I would sure like to see something like that!

On Fri, Dec 21, 2018 at 12:06 PM alanfo  wrote:

> Some languages which don't support the conditional operator or if/else
> expressions have an Iif function (or similar) instead.
>
> If generics are added to Go, it might be worth including something like
> this in the standard library to cut down on boilerplate for simple cases:
>
> // in a package called 'gen' say
> func Iif(type T) (cond bool, t1, t2 T) T {
> if cond {
> return t1
> }
> return t2
> }
>
> // usage
> x := 3
> ...
> y := gen.Iif(x > 2, 4, 5) // T inferred to be int, assigns 4 to y
>
> You can, of course, do this now with interface{} but it's not type-safe
> and requires a type assertion on assignment.
>
> A drawback is that it would require the overhead of a function call unless
> the Go compiler could inline simple stuff such as this.
>
> Alan
>
> On Wednesday, December 19, 2018 at 8:09:35 PM UTC, Viktor Kojouharov wrote:
>>
>> Hello,
>>
>> I've tried and failed at finding any previous discussion on this topic,
>> so do point me to one if it exists.
>>
>> I'm interested to know whether it was considered (I can't imagine that it
>> wasn't) for if and switch statements to be expressions instead, and if so,
>> why were they ultimately left as statements. It seems to me that having
>> them as expressions will not cause a significant change in how they are
>> ultimately used, mostly because other languages that do support such
>> expressions do not exhibit this behaviour either. Nor is such a change
>> strictly backwards incompatible, since any expression is also technically a
>> statement as well, via the ExpressionStmt grammar rule. Such expressions
>> also cover a simple feature which a lot of people new to the language are
>> looking for, and most of us have abused in other languages - ternary
>> operators. The Go FAQ states that if-elses are clearer, if longer, which I
>> definitely agree with. Yet it seems that an if expression would retain its
>> readability, if not outright increase it, while allowing for terser
>> assignments. The reason being that a chunk of repeatable code (for example
>> assigning to the same variable in every logical branch) would be moved out
>> of the whole block, thus highlighting the value.
>>
>> What if the spec defines that if all if-else blocks / all switch case
>> clauses contain only single expression, they would be expressions rather
>> than statements. How would that negatively impact the language, in a way
>> that can't already be reproduced?
>>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


[go-nuts] Re: Go 1.11.4 and Go 1.10.7 are released

2018-12-17 Thread mark
I think we're just waiting on this PR to get 
merged: https://github.com/docker-library/official-images/pull/5197

And then the official docker images should start building automatically.

On Monday, December 17, 2018 at 1:27:01 PM UTC-5, Elliott Polk wrote:
>
> Will there be a Docker image update for go1.11.4? I know that .4 was a 
> quick patch, just wanted to make sure the Docker image is on the deployment 
> path as well.
>
> On Friday, December 14, 2018 at 8:49:20 PM UTC-5, Filippo Valsorda wrote:
>>
>> Hello gophers, 
>>
>> We have just released Go versions 1.11.4 and 1.10.7, minor point 
>> releases. 
>>
>> These releases include fixes to cgo, the compiler, linker, runtime, 
>> documentation, go command, and the net/http and go/types packages. 
>> They include a fix to a bug introduced in Go 1.11.3 and Go 1.10.6 
>> that broke "go get" for import path patterns containing "...". 
>>
>> View the release notes for more information: 
>> https://golang.org/doc/devel/release.html#go1.11.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.11.4" and build as usual. 
>>
>> Thanks to everyone who contributed to the release. 
>>
>> Alla prossima, 
>> Filippo 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.
For more options, visit https://groups.google.com/d/optout.


Re: [go-nuts] Re: pass interface

2018-12-10 Thread Mark Volkmann
Thanks so much Dan!

---
R. Mark Volkmann
Object Computing, Inc.

> On Dec 10, 2018, at 8:34 PM, Dan Kortschak  wrote:
> 
> https://play.golang.org/p/VWPb_AcgUrl
> 
>> On Mon, 2018-12-10 at 20:14 -0600, Mark Volkmann wrote:
>> Here is some code that shows a part of what I'm trying to do.
>> https://goplay.space/#8piYtjsqveZ
>> 
>> package main
>> 
>> import (
>> "fmt"
>> "reflect"
>> )
>> 
>> type Shape interface {
>> Area() float64
>> Rotate(angle float64)
>> Translate(x, y float64)
>> }
>> 
>> func ReportInterface(intfPtr interface{}) {
>> fmt.Println("type is", reflect.TypeOf(intfPtr)) // *main.Shape
>> value := reflect.ValueOf(intfPtr)
>> fmt.Println("value is", value)// 
>> fmt.Println("method count is", value.NumMethod()) // 0, Why not 3?
>> }
>> 
>> func main() {
>> var ptr *Shape
>> ReportInterface(ptr)
>> }
>> 
>> On Mon, Dec 10, 2018 at 3:28 PM Dan Kortschak 
>> wrote:
>> 
>>> 
>>> No, it is possible, but you need to pass the pointer to the
>>> interface.
>>> You can then use reflect to interrogate the interface value.
>>> 
>>> The bigger question, and one that would help here would be what is
>>> it
>>> that you are actually trying to achieve.
>>> 
>>>> On Mon, 2018-12-10 at 08:53 -0600, Mark Volkmann wrote:
>>>> 
>>>> Yes, this is what I'm trying to do!
>>>> Perhaps this is not possible.
>>>> 
>>>> On Sun, Dec 9, 2018 at 10:34 PM Robert Engels >>> com>
>>>> wrote:
>>>> 
>>>>> 
>>>>> 
>>>>> I think what the OP wants is:
>>>>> 
>>>>> type A interface{}
>>>>> type B interface{}
>>>>> 
>>>>> ...
>>>>> PrintInterface(A)
>>>>> 
>>>>> Meaning they want to pass the interface definition to some
>>>>> method.
>>>>> 
>>>>> At least that’s what I am guessing.
>>>>> 
>>>>> On Dec 9, 2018, at 9:22 PM, Space A. 
>>>>> wrote:
>>>>> 
>>>>> reflect/* is a bit tricky. Use pointer to get interface itself.
>>>>> 
>>>>> package main
>>>>> 
>>>>> import (
>>>>> "fmt"
>>>>> "reflect"
>>>>> )
>>>>> 
>>>>> func main() {
>>>>> test := interface{}("test")
>>>>> printInterfaceValue(test)
>>>>> }
>>>>> 
>>>>> func printInterfaceValue(i interface{}) {
>>>>> switch testing := i.(type) {
>>>>> case interface{}:
>>>>> fmt.Println("is interface, with value:", testing)
>>>>> case string:
>>>>> fmt.Println("is not interface")
>>>>> }
>>>>> 
>>>>> fmt.Println("reflect.Type is", reflect.TypeOf().Elem())
>>>>> }
>>>>> 
>>>>> Output:
>>>>> 
>>>>> is interface, with value: test
>>>>> reflect.Type is interface {}
>>>>> 
>>>>> 
>>>>> 
>>>>> 
>>>>> 
>>>>> 
>>>>> понедельник, 10 декабря 2018 г., 5:05:12 UTC+3 пользователь
>>>>> Robert
>>>>> Engels
>>>>> написал:
>>>>>> 
>>>>>> 
>>>>>> 
>>>>>> I mean reflect.Type not a type that is an interface.
>>>>>> 
>>>>>> On Dec 9, 2018, at 6:53 PM, Space A. 
>>>>>> wrote:
>>>>>> 
>>>>>> Of course. When you "pass a value whose type implements the
>>>>>> interface" as
>>>>>> an interface argument to a function, you in fact pass an
>>>>>> *interface*.
>>>>>> 
>>>>>> 
>>>>>> воскресенье, 9 декабря 2018 г., 23:23:41 UTC+3 пользователь
>>>>>> Mark
>>>>>> Volkmann
>>>>>> написал:
>>>>>>> 
>>>>>>> 
>>>>>>> 
>>>>>>> Is it possible to pass an interface to a function in Go? I
>>>>>>> don’t want to
>>>>>>> pass a value whose type implements the interface, I want to
>>>>>>> pass the
>>>>>>> interface.
>>>>>>> 
>>>>>>> --
>>>>>>> R. Mark Volkmann
>>>>>>> Object Computing, Inc.
>>>>>>> 
>>>>>> --
>>>>>> You received this message because you are subscribed to the
>>>>>> Google Groups
>>>>>> "golang-nuts" group.
>>>>>> To unsubscribe from this group and stop receiving emails from
>>>>>> it,
>>>>>> send an
>>>>>> email to golang-nuts...@googlegroups.com.
>>>>>> For more options, visit https://groups.google.com/d/optout.
>>>>>> 
>>>>>> --
>>>>> You received this message because you are subscribed to the
>>>>> Google
>>>>> Groups
>>>>> "golang-nuts" group.
>>>>> To unsubscribe from this group and stop receiving emails from
>>>>> it,
>>>>> send an
>>>>> email to golang-nuts+unsubscr...@googlegroups.com.
>>>>> For more options, visit https://groups.google.com/d/optout.
>>>>> 
>>>>> --
>>>>> You received this message because you are subscribed to the
>>>>> Google
>>>>> Groups
>>>>> "golang-nuts" group.
>>>>> To unsubscribe from this group and stop receiving emails from
>>>>> it,
>>>>> send an
>>>>> email to golang-nuts+unsubscr...@googlegroups.com.
>>>>> For more options, visit https://groups.google.com/d/optout.
>>>>> 
>>>> --
>>>> R. Mark Volkmann
>>>> Object Computing, Inc.
>>>> 
> 
>> 

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


Re: [go-nuts] Re: pass interface

2018-12-10 Thread Mark Volkmann
Here is some code that shows a part of what I'm trying to do.
https://goplay.space/#8piYtjsqveZ

package main

import (
"fmt"
"reflect"
)

type Shape interface {
Area() float64
Rotate(angle float64)
Translate(x, y float64)
}

func ReportInterface(intfPtr interface{}) {
fmt.Println("type is", reflect.TypeOf(intfPtr)) // *main.Shape
value := reflect.ValueOf(intfPtr)
fmt.Println("value is", value)// 
fmt.Println("method count is", value.NumMethod()) // 0, Why not 3?
}

func main() {
var ptr *Shape
ReportInterface(ptr)
}

On Mon, Dec 10, 2018 at 3:28 PM Dan Kortschak  wrote:

> No, it is possible, but you need to pass the pointer to the interface.
> You can then use reflect to interrogate the interface value.
>
> The bigger question, and one that would help here would be what is it
> that you are actually trying to achieve.
>
> On Mon, 2018-12-10 at 08:53 -0600, Mark Volkmann wrote:
> > Yes, this is what I'm trying to do!
> > Perhaps this is not possible.
> >
> > On Sun, Dec 9, 2018 at 10:34 PM Robert Engels 
> > wrote:
> >
> > >
> > > I think what the OP wants is:
> > >
> > > type A interface{}
> > > type B interface{}
> > >
> > > ...
> > > PrintInterface(A)
> > >
> > > Meaning they want to pass the interface definition to some method.
> > >
> > > At least that’s what I am guessing.
> > >
> > > On Dec 9, 2018, at 9:22 PM, Space A.  wrote:
> > >
> > > reflect/* is a bit tricky. Use pointer to get interface itself.
> > >
> > > package main
> > >
> > > import (
> > > "fmt"
> > > "reflect"
> > > )
> > >
> > > func main() {
> > > test := interface{}("test")
> > > printInterfaceValue(test)
> > > }
> > >
> > > func printInterfaceValue(i interface{}) {
> > > switch testing := i.(type) {
> > > case interface{}:
> > > fmt.Println("is interface, with value:", testing)
> > > case string:
> > > fmt.Println("is not interface")
> > > }
> > >
> > > fmt.Println("reflect.Type is", reflect.TypeOf().Elem())
> > > }
> > >
> > > Output:
> > >
> > > is interface, with value: test
> > > reflect.Type is interface {}
> > >
> > >
> > >
> > >
> > >
> > >
> > > понедельник, 10 декабря 2018 г., 5:05:12 UTC+3 пользователь Robert
> > > Engels
> > > написал:
> > > >
> > > >
> > > > I mean reflect.Type not a type that is an interface.
> > > >
> > > > On Dec 9, 2018, at 6:53 PM, Space A.  wrote:
> > > >
> > > > Of course. When you "pass a value whose type implements the
> > > > interface" as
> > > > an interface argument to a function, you in fact pass an
> > > > *interface*.
> > > >
> > > >
> > > > воскресенье, 9 декабря 2018 г., 23:23:41 UTC+3 пользователь Mark
> > > > Volkmann
> > > > написал:
> > > > >
> > > > >
> > > > > Is it possible to pass an interface to a function in Go? I
> > > > > don’t want to
> > > > > pass a value whose type implements the interface, I want to
> > > > > pass the
> > > > > interface.
> > > > >
> > > > > --
> > > > > R. Mark Volkmann
> > > > > Object Computing, Inc.
> > > > >
> > > > --
> > > > You received this message because you are subscribed to the
> > > > Google Groups
> > > > "golang-nuts" group.
> > > > To unsubscribe from this group and stop receiving emails from it,
> > > > send an
> > > > email to golang-nuts...@googlegroups.com.
> > > > For more options, visit https://groups.google.com/d/optout.
> > > >
> > > > --
> > > You received this message because you are subscribed to the Google
> > > Groups
> > > "golang-nuts" group.
> > > To unsubscribe from this group and stop receiving emails from it,
> > > send an
> > > email to golang-nuts+unsubscr...@googlegroups.com.
> > > For more options, visit https://groups.google.com/d/optout.
> > >
> > > --
> > > You received this message because you are subscribed to the Google
> > > Groups
> > > "golang-nuts" group.
> > > To unsubscribe from this group and stop receiving emails from it,
> > > send an
> > > email to golang-nuts+unsubscr...@googlegroups.com.
> > > For more options, visit https://groups.google.com/d/optout.
> > >
> >
> > --
> > R. Mark Volkmann
> > Object Computing, Inc.
> >
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


Re: [go-nuts] Re: pass interface

2018-12-10 Thread Mark Volkmann
Yes, this is what I'm trying to do!
Perhaps this is not possible.

On Sun, Dec 9, 2018 at 10:34 PM Robert Engels  wrote:

> I think what the OP wants is:
>
> type A interface{}
> type B interface{}
>
> ...
> PrintInterface(A)
>
> Meaning they want to pass the interface definition to some method.
>
> At least that’s what I am guessing.
>
> On Dec 9, 2018, at 9:22 PM, Space A.  wrote:
>
> reflect/* is a bit tricky. Use pointer to get interface itself.
>
> package main
>
> import (
> "fmt"
> "reflect"
> )
>
> func main() {
> test := interface{}("test")
> printInterfaceValue(test)
> }
>
> func printInterfaceValue(i interface{}) {
> switch testing := i.(type) {
> case interface{}:
> fmt.Println("is interface, with value:", testing)
> case string:
> fmt.Println("is not interface")
> }
>
> fmt.Println("reflect.Type is", reflect.TypeOf().Elem())
> }
>
> Output:
>
> is interface, with value: test
> reflect.Type is interface {}
>
>
>
>
>
>
> понедельник, 10 декабря 2018 г., 5:05:12 UTC+3 пользователь Robert Engels
> написал:
>>
>> I mean reflect.Type not a type that is an interface.
>>
>> On Dec 9, 2018, at 6:53 PM, Space A.  wrote:
>>
>> Of course. When you "pass a value whose type implements the interface" as
>> an interface argument to a function, you in fact pass an *interface*.
>>
>>
>> воскресенье, 9 декабря 2018 г., 23:23:41 UTC+3 пользователь Mark Volkmann
>> написал:
>>>
>>> Is it possible to pass an interface to a function in Go? I don’t want to
>>> pass a value whose type implements the interface, I want to pass the
>>> interface.
>>>
>>> --
>>> R. Mark Volkmann
>>> Object Computing, Inc.
>>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to golang-nuts...@googlegroups.com.
>> For more options, visit https://groups.google.com/d/optout.
>>
>> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


[go-nuts] pass interface

2018-12-09 Thread Mark Volkmann
Is it possible to pass an interface to a function in Go? I don’t want to
pass a value whose type implements the interface, I want to pass the
interface.

-- 
R. Mark Volkmann
Object Computing, Inc.

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


[go-nuts] getting a reflect.Type for a type

2018-12-05 Thread Mark Volkmann
I can get a reflect.Type for a variable with the following: myType :=
reflect.TypeOf(myVariable)

How can I get a reflect.Type for a type I have defined?
For example: type MyThing struct { …bunch of fields… }
I need to get a reflect.Type that describes the MyThing type.

The best I can find is this: myThingType :=
reflect.TypeOf(new(MyThing)).Elem()

I seems odd that I have to create one with new, getting a pointer to it,
and then ask for the type of the thing in points to (with Elem) in order to
get what I need.

-- 
R. Mark Volkmann
Object Computing, Inc.

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


[go-nuts] Is it possible with go modules to `go get` the ref (not the SHA) of an GitHub PR?

2018-12-04 Thread mark
I have a private github repository that depends on an open source github 
repository. There's an open PR in the open source repo, and I'd like to `go 
get` that change to test it locally in my private repo.

Normally, when I update the open source repository, I can just run `go get 
github.com/MY_ORG/MY_OSS_REPO@`. If I use the full SHA of 
the most recent commit in the PR, this works fine. 

But I can't get it to work for variations of `go get 
github.com/ORG/REPO@{refs/,}pull/123{,/head}`, following the instructions 
at https://help.github.com/articles/checking-out-pull-requests-locally/ 
and https://stackoverflow.com/q/6743514. I get the impression that there's 
something special about the pull refs that you have to request them 
directly, since they don't get pulled during a plain `git fetch` during 
normal repository work.

I would prefer to use the direct PR ref, rather than the SHA. I can figure 
out how to script retrieving the SHA from the PR number, so I have a valid 
workaround, but I thought I'd ask here to see if maybe I missed some 
obvious way to go get by PR number.

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


Re: [go-nuts] pointer dereference optimization in loops

2018-11-30 Thread Mark Volkmann
I think I failed to come up with a good code example. But suppose I need to
do something with a pointer inside a loop that really does require
dereferencing it and the pointer never changes inside the loop. In that
case will the Go compiler optimize that so the dereference doesn't happen
in each loop iteration?

On Fri, Nov 30, 2018 at 11:36 AM Jan Mercl <0xj...@gmail.com> wrote:

>
> On Fri, Nov 30, 2018 at 6:16 PM Mark Volkmann 
> wrote:
>
> > Will the Go compiler optimize the pointer dereference so it doesn't
> happen in every loop iteration? If not, is it common practice to do that
> outside the loop like this?
> >
> > myValue := *myPtr
> > for _, v := range values {
> > fmt.Printf("%v %v\n", myValue, v)
> > }
>
> There's no pointer dereference inside the loop. But there's an allocation
> inside the loop, on every iteration, that puts a pointer to a copy of
> myValue into an interface{} that's passed to fmt.Printf. The allocation can
> be probably avoided:
>
> myValue := interface{}(*myPtr)
> for _, v := range values {
> fmt.Printf("%v %v\n", myValue, v)
> }
>
> But the %v verb handle pointers in many cases well. If that holds for the
> type of *myPtr then simply:
>
> for _, v := range values {
> fmt.Printf("%v %v\n", myPtr, v)
> }
>
> is what could be good enough.
>
> --
>
> -j
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


[go-nuts] pointer dereference optimization in loops

2018-11-30 Thread Mark Volkmann
Suppose myPtr is a pointer and I write code like this:

for _, v := range values {
fmt.Printf("%v %v\n", *myPtr, v)
}

Will the Go compiler optimize the pointer dereference so it doesn't happen
in every loop iteration? If not, is it common practice to do that outside
the loop like this?

myValue := *myPtr
for _, v := range values {
fmt.Printf("%v %v\n", myValue, v)
}

-- 
R. Mark Volkmann
Object Computing, Inc.

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


Re: [go-nuts] go language sensitive editor?

2018-11-20 Thread Mark Volkmann
I'm sure you'll get lots of opinions on this. VS Code is working great for
me.

On Tue, Nov 20, 2018 at 2:52 PM Pat Farrell  wrote:

> I know, this is both a FAQ and an unanswerable question. I'm an old
> programmer who has used nearly every editor known to man. I am not a fan of
> whole-universe IDEs, but can use them. I also speak vi/vim pretty fluently.
>
> What editors do folks use for go? I'd like something that can complete
> function names, understand imports, and give some assistance.
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


Re: [go-nuts] [ANN] Koazee a library inspired by functional programming and lazy evaluation that takes the hassle out of working with arrays

2018-11-13 Thread Mark Volkmann
I don't get the impression that we are going to see generics in Go anytime
soon. I'll be surprised to see it before 2020. So until then, I like having
a library like this even if it uses reflection.

On Tue, Nov 13, 2018 at 2:14 PM roger peppe  wrote:

> It's obvious that you've put a lot of effort into this! Here's some
> feedback.
>
> I have to say this first: this *is* a very non-Go-idiomatic API. It's
> fundamentally based around reflection, and reflection in Go is generally
> considered to be best avoided apart from some core libraries. Calling a
> function with reflect is orders of magnitude slower than calling it
> directly, and the lack of compiler type checking can make for code that's
> hard to understand when it goes wrong. So I wouldn't use this in production
> code.
>
> That said, it's a fun API and a great way to experiment with some of the
> things that can be done in Go if we sacrifice compile-type type checking.
>
> Taking it at face value, here are a few random thoughts:
>
> - improve the doc comments. Go automatically generates documentation for
> you (for example https://godoc.org/github.com/wesovilabs/koazee/stream)
> and that's the usual place for people to read package documentation.
> Everything that's exported should have a relevant doc comment. There
> shouldn't be any need to generate custom API documentation.
>
> - avoid making public methods return private types. When a public method
> returns a private type, the documentation fails because it does not display
> methods on private types.
>
> - it's almost always better to use the builtin sort package (
> https://golang.org/pkg/sort) rather than rolling your own.
>
> - it's probably best not to use an arbitrary definition of equality
> (stream.equalsValues), but to either use plain "==" or accept an equality
> function.
>
> - it would be nice for it to work on arbitrary streams. This actually
> isn't too hard. Here's a way of doing it that works on an arbitrary
> Iterator interface, so it can iterate over channels, bufio.Scanner, etc.
> https://play.golang.org/p/PXHuD1pR5uC
>
> Finally, if/when generics eventually make it into Go, this kind of API
> will no longer have a huge overhead. I think I'd probably wait until
> then... :)
>
>   cheers,
> rog.
>
> On Sun, 11 Nov 2018 at 19:27, Iván Corrales Solera <
> ivan.corrales.sol...@gmail.com> wrote:
>
>> Hey guys, last weeks I've been working on Koazee and I just released a
>> very first version Titi, v0.0.1 . Koazee is a golang library inspired in
>> Lazy evaluation and functional programming that provides us a rich set of
>> operations that can be done over arrays. If you like the clean code and the
>> functional programming I am sure you enjoy it!
>>
>> Documentation is hosted http://wesovilabs.com/koazee/
>>
>> And the full code can be found on Github,
>> https://github.com/wesovilabs/koazee
>> Any feedback or recommendation will be appreciated! Cheers
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to golang-nuts+unsubscr...@googlegroups.com.
>> For more options, visit https://groups.google.com/d/optout.
>>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


Re: [go-nuts] [ANN] Koazee a library inspired by functional programming and lazy evaluation that takes the hassle out of working with arrays

2018-11-11 Thread Mark Volkmann
Wow, this is a wonderful library! Thanks so much for creating this!

---
R. Mark Volkmann
Object Computing, Inc.

> On Nov 11, 2018, at 1:27 PM, Iván Corrales Solera 
>  wrote:
> 
> Hey guys, last weeks I've been working on Koazee and I just released a very 
> first version Titi, v0.0.1 . 
> 
> Koazee is a golang library inspired in Lazy evaluation and functional 
> programming that provides us a rich set of operations that can be done over 
> arrays.  If you like the clean code and the functional programming I am sure 
> you enjoy it!
> 
> Documentation is hosted http://wesovilabs.com/koazee/
> 
> And the full code can be found on Github, https://github.com/wesovilabs/koazee
> 
> Any feedback or recommendation will be appreciated!
> 
> Cheers
> -- 
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

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


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

2018-11-08 Thread mark
> What you really want is the stack trace for the goroutine that created 
the leaking goroutine, at the time that the leak was created.

GODEBUG=tracebackancestors=1 ought to show that. tracebackancestors is new 
in Go 1.11 IIRC.

https://golang.org/pkg/runtime/#hdr-Environment_Variables



On Thursday, November 8, 2018 at 9:51:12 AM UTC-8, Jake Montgomery wrote:
>
> I would point out that this *is *the whole stack trace *of the goroutine*. 
> In fact, the actual stack trace is just the first line, since the goroutine 
> in question is only one function deep. If you are breaking into your 
> program after the leaking has started, then the function that created the 
> goroutine has long since exited, and its stack no longer exists. 
>
> What you really want is the stack trace for the goroutine that created the 
> leaking goroutine, at the time that the leak was created. I suggest you put 
> a break point on (*Transport).dialConn, or 
> /usr/local/go/src/net/http/transport.go:1117 and run your program to see 
> where these are being created. You might also be able to figure it out by 
> looking at the go library source code and tracing back from 
> (*Transport).dialConn. In any case, that should give you a place to start.
>
> Good Luck. 
>
> On Tuesday, November 6, 2018 at 10:55:24 PM UTC-5, rickyu...@gmail.com 
> wrote:
>>
>> I have a lot of leaking goroutines in my code over a span of time. I am 
>> trying to debug it but I can't seem to figure out from where these are 
>> occuring from.
>> Any help in finding the source is helpful.
>>
>>
>> goroutine 2329 [select, 1281 minutes]:
>> net/http.(*persistConn).readLoop(0xc420a80120)
>>  /usr/local/go/src/net/http/transport.go:1599 +0x9ec
>> created by net/http.(*Transport).dialConn
>>  /usr/local/go/src/net/http/transport.go:1117 +0xa35
>>
>>
>> Thanks,
>>
>>

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


Re: [go-nuts] How can I identify the default value of the -p build flag?

2018-11-02 Thread Mark Rushakoff
Thanks. That confirms that Go thinks there are 36 CPUs available in that
environment.

I'm still a bit surprised that there's no way to invoke the go executable
to get the value of runtime.NumCPU. A quick grep through src/cmd looks like
it isn't directly exposed anywhere. I might file an issue requesting that
to be exposed, but I'll think on it a bit first.

On Fri, Nov 2, 2018 at 3:58 PM Ian Lance Taylor  wrote:

> On Fri, Nov 2, 2018 at 2:29 PM,   wrote:
> >
> > This is somewhat an XY problem, so let me preface with the X:
> >
> > We infrequently see `/usr/local/go/pkg/tool/linux_amd64/link: signal:
> > killed` when running `go test` for our project on CircleCI, running Go
> > 1.11.1.
> >
> > As far as I can tell, that killed signal is due to OOMing. The comment at
> > https://github.com/golang/go/issues/26186#issuecomment-427482208 says he
> > worked around that same symptom by using -p=8.
> >
> > I could easily switch our command to `go test -p=8`, but I want to
> > understand what value is used when the -p flag isn't provided.
> >
> > All `go help build` has to say is:
> >
> >> -p n
> >> the number of programs, such as build commands or
> >> test binaries, that can be run in parallel.
> >> The default is the number of CPUs available.
> >
> > Our particular build seems to fall under this part of the Circle docs:
> > https://circleci.com/docs/2.0/configuration-reference/#resource_class
> >
> > I think we're on a 2 vCPU setup, but the docs go on to state:
> >
> >> Java, Erlang and any other languages that introspect the /proc directory
> >> for information about CPU count may require additional configuration to
> >> prevent them from slowing down when using the CircleCI 2.0 resource
> class
> >> feature. Programs with this issue may request 32 CPU cores and run
> slower
> >> than they would when requesting one core. Users of languages with this
> issue
> >> should pin their CPU count to their guaranteed CPU resources.
> >
> > Skimming through the code, it looks like Go on Linux should be using
> > sched_getaffinity, so I don't think it's inspecting /proc. But maybe I
> read
> > things wrong.
> >
> >
> > Is the `go help build` output "number of CPUs available" GOMAXPROCS or
> > something else? I was somewhat surprised to see that `go env` doesn't
> emit
> > GOMAXPROCS.
> >
> >
> > I also tried locally running `go test -x` to see if that had any output
> to
> > hint towards what the default value of -p would be, but if that detail
> was
> > in the output, I missed it.
>
> To see the default value used for the -p option, run this program:
>
> package main
>
> import (
> "fmt"
> "runtime"
> )
>
> func main() {
> fmt.Println(runtime.NumCPU())
> }
>
> Ian
>

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


[go-nuts] How can I identify the default value of the -p build flag?

2018-11-02 Thread mark
This is somewhat an XY problem, so let me preface with the X:

We infrequently see `/usr/local/go/pkg/tool/linux_amd64/link: signal: 
killed` when running `go test` for our project on CircleCI, running Go 
1.11.1.

As far as I can tell, that killed signal is due to OOMing. The comment 
at https://github.com/golang/go/issues/26186#issuecomment-427482208 says he 
worked around that same symptom by using -p=8.

I could easily switch our command to `go test -p=8`, but I want to 
understand what value is used when the -p flag isn't provided.

All `go help build` has to say is:

> -p n
> the number of programs, such as build commands or
> test binaries, that can be run in parallel.
> The default is the number of CPUs available.

Our particular build seems to fall under this part of the Circle 
docs: https://circleci.com/docs/2.0/configuration-reference/#resource_class

I think we're on a 2 vCPU setup, but the docs go on to state:

> Java, Erlang and any other languages that introspect the /proc directory 
for information about CPU count may require additional configuration to 
prevent them from slowing down when using the CircleCI 2.0 resource class 
feature. Programs with this issue may request 32 CPU cores and run slower 
than they would when requesting one core. Users of languages with this 
issue should pin their CPU count to their guaranteed CPU resources.

Skimming through the code, it looks like Go on Linux should be using 
sched_getaffinity, so I don't think it's inspecting /proc. But maybe I read 
things wrong.


Is the `go help build` output "number of CPUs available" GOMAXPROCS or 
something else? I was somewhat surprised to see that `go env` doesn't emit 
GOMAXPROCS.


I also tried locally running `go test -x` to see if that had any output to 
hint towards what the default value of -p would be, but if that detail was 
in the output, I missed 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.
For more options, visit https://groups.google.com/d/optout.


Re: [go-nuts] Go modules and replace

2018-10-19 Thread Mark Volkmann
I see though that "go mode edit" really wants there to be a dot in the
first part of the import path.
Where can I read about that requirement?

On Fri, Oct 19, 2018 at 6:30 PM Mark Volkmann 
wrote:

> Thank you so much! I actually got it to work without having a dot in the
> first part of the import path.
> It seems the only thing I was missing was this line in mod.go for the demo
> code:
> require foo/bar v0.0.0
> I just had the replace directive line without a corresponding require
> directive.
>
> On Fri, Oct 19, 2018 at 6:13 PM Paul Jolly  wrote:
>
>> Hi Mark,
>>
>> When importing a module package, the first element in the path must
>> contain a ".". Hence "foo" is invalid. Here is a working example:
>>
>> $ cd $HOME
>> $ mkdir bar
>> $ cd bar
>> $ go mod init example.com/bar
>> go: creating new go.mod: module example.com/bar
>> $ cat <bar.go
>> package bar
>> import "fmt"
>> func Hello() {
>> fmt.Println("Hello from bar!")
>> }
>> EOD
>> $ cd $HOME
>> $ mkdir foo
>> $ cd foo
>> $ go mod init example.com/foo
>> go: creating new go.mod: module example.com/foo
>> $ cat <main.go
>> package main
>>
>> import "example.com/bar"
>>
>> func main() {
>> bar.Hello()
>> }
>> EOD
>> $ go mod edit -require=example.com/bar@v0.0.0 -replace=
>> example.com/bar=$HOME/bar
>> $ cat go.mod
>> module example.com/foo
>>
>> require example.com/bar v0.0.0
>>
>> replace example.com/bar => /root/bar
>> $ go run .
>> Hello from bar!
>> On Fri, 19 Oct 2018 at 21:42, Mark Volkmann 
>> wrote:
>> >
>> > I have a simple demo application that wants to use a package that is on
>> my local file system.
>> > The code for the package is in /Users/Mark/foo/bar.
>> > This directory contains the file bar.go which contains:
>> >
>> > package bar
>> > import "fmt"
>> > func Hello() {
>> > fmt.Println("Hello from bar!")
>> > }
>> >
>> > It also contains the file go.mod which just contains:
>> >
>> > module bar
>> >
>> > The demo application in another directory imports this as "foo/bar" in
>> the file main.go.
>> > It has a go.mod file that contains the following:
>> >
>> > module demo
>> > replace foo/bar => /Users/Mark/foo/bar
>> >
>> > When I enter "go run main.go" in the directory of the demo code I get
>> > build demo: cannot find module for path foo/bar
>> >
>> > Is there something wrong with my use of the "replace" directive?
>> >
>> > None of this code is under the directory pointed to by GOPATH because
>> I'm trying to use Go modules for everything in this demo.
>> >
>> > --
>> > R. Mark Volkmann
>> > Object Computing, Inc.
>> >
>> > --
>> > You received this message because you are subscribed to the Google
>> Groups "golang-nuts" group.
>> > To unsubscribe from this group and stop receiving emails from it, send
>> an email to golang-nuts+unsubscr...@googlegroups.com.
>> > For more options, visit https://groups.google.com/d/optout.
>>
>
>
> --
> R. Mark Volkmann
> Object Computing, Inc.
>


-- 
R. Mark Volkmann
Object Computing, Inc.

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


  1   2   >