Skip to content

Commit

Permalink
types: add Stringer implementation for List
Browse files Browse the repository at this point in the history
Signed-off-by: Sebastien Binet <[email protected]>
  • Loading branch information
sbinet committed Nov 24, 2023
1 parent 9bac659 commit 62f65b4
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
21 changes: 20 additions & 1 deletion types/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

package types

import "fmt"
import (
"fmt"
"strings"
)

// ListAppender is implemented by any value that exhibits a list-like
// behaviour, allowing arbitrary values to be appended.
Expand Down Expand Up @@ -59,3 +62,19 @@ func (*List) Call(args ...interface{}) (interface{}, error) {
}
return nil, fmt.Errorf("List: invalid arguments: %#v", args)
}

func (l *List) String() string {
if l == nil {
return "nil"
}
o := new(strings.Builder)
o.WriteString("[")
for i, v := range *l {
if i > 0 {
o.WriteString(", ")
}
fmt.Fprintf(o, "%v", v)
}
o.WriteString("]")
return o.String()
}
23 changes: 23 additions & 0 deletions types/list_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
// Copyright 2023 NLP Odyssey Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package types

import (
"bytes"
"fmt"
"testing"
)

Expand All @@ -15,3 +21,20 @@ func TestCall(t *testing.T) {
t.Errorf("expected %v, actual: %v", expected, actual)
}
}

func TestListStringer(t *testing.T) {
pylist := func(sli ...interface{}) *List {
return NewListFromSlice(sli)
}

lst := pylist(pylist(), pylist(1), pylist(2, 3), pylist(pylist(4, 5), 6))

buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%v", lst)
got := buf.String()
want := "[[], [1], [2, 3], [[4, 5], 6]]"

if got != want {
t.Fatalf("got= %q\nwant=%q", got, want)
}
}

0 comments on commit 62f65b4

Please sign in to comment.