Failing to List.PushBack - list

Take a look at the following source code:
import "container/list"
type Stream struct {
list list.List
}
func (s Stream) Append(value interface{}) {
log.Println(s.list.Len())
s.list.PushBack(value)
log.Println(s.list.Len())
}
This code will keep on printing 0 and 1 all the time. Am I doing it wrong?

You're copying your Stream and List values in the Append method.
Either make Append a pointer receiver
func (s *Stream) Append(value interface{}) {
or make Stream.list a *list.List
type Stream struct {
list *list.List
}

Related

Pass list of one of two structures to the function

New in Go, couldn't find any intuitive way of doing that.
I have such piece of code
tx = getTx()
for _, record := range tx.a {
// do a lot with record.Important
}
for _, record := range tx.b {
// do a lot with record.Important
}
for _, record := range tx.c {
// do a lot with record.Important
}
And the following structs:
type Record1 struct {
// fields of Record1
Important string
}
type Record2 struct {
// fields of Record1
Important string
}
type TX struct {
a []Record1
b []Record1
c []Record2
}
Now the logical is to extract every for logic into the function:
func helper(records) { // Here is the problem
// do a lot with record.Important
}
Problem:
records is a []Record1 or []Record2 type. But it looks like Union types doesn't exists in Golang. So I thought I could pass []string into the helper, but cannot even find an elegant way to get something equivalent to map(lambda r: r.Important, tx.a). There is no high order map function, no list comprehesion. I am not convinced to use raw for loop to solve that.
One approach to do the loop across multiple types is to use interfaces together with generics. Have each Record type implement a getter method for the important field. Then declare an interface that includes that getter method in its method set. Then you can make your helper generic by declaring the interface as its type parameter.
func (r Record1) GetImportant() string { return r.Important }
func (r Record2) GetImportant() string { return r.Important }
type ImportantGetter interface {
GetImporant() string
}
func helper[T ImportantGetter](s []T) {
for _, v := range s {
_ = v.GetImportant()
}
}
Unless I'm misunderstanding your question, it seems like you want to extract all the values in column X from a set of records and then pass those values in as a slice to some function - I'm basing my assumption on your wish that go had something like map().
If what you're after is type-agnosticism, you could certainly use an interface approach like that suggested by mkopriva, but you aren't going to get out of using a for loop - iteration over list types is core to idiomatic go. If you need a mapping function, you're going to have to write one that performs the mapping you want.
I'd note that you do not need generics to do what mkopriva suggests, you can just use an interface without muddying the waters with generics go playground:
package main
import "fmt"
type Record1 struct {
Important string
}
type Record2 struct {
Important string
}
func (r Record1) GetImportant() string { return r.Important }
func (r Record2) GetImportant() string { return r.Important }
type ImportantGetter interface {
GetImportant() string
}
func helper(s []ImportantGetter) {
for _, v := range s {
fmt.Println(v.GetImportant())
}
}
func main() {
records := []ImportantGetter{Record1{Important: "foo"}, Record2{Important: "bar"}}
helper(records)
}
Another approach to the type-agnosticism, and one that's a bit more (IMHO) idiomatic for "I expect all of these types to have a common property," is to use struct embedding and type assertions to build your own Map() function up go playground:
type CommonFields struct {
Important string
}
type Record1 struct {
CommonFields
FieldSpecificToRecord1 string
}
type Record2 struct {
CommonFields
FieldSpecificToRecord2 int
}
func main() {
r1 := Record1{
CommonFields{Important: "I'm r1!"},
"foo",
}
r2 := Record2{
CommonFields{Important: "I'm r2!"},
5,
}
records := []interface{}{r1, r2, "this is not a valid record type"}
fmt.Println(Map(records))
}
func Map(source []interface{}) []string {
destination := make([]string, len(source))
for i, sourceRecord := range source {
if rr, ok := sourceRecord.(Record1); ok {
destination[i] = rr.Important
} else if rr, ok := sourceRecord.(Record2); ok {
destination[i] = rr.Important
} else {
destination[i] = "undefined"
}
}
return destination
}
You'd likely want to make your implementation of Map() accept an argument specifying the field to extract to conform to what you have in other languages, or possibly even just pass in a helper function which does most of the type-specific value extraction.

Data bytes to sockaddr conversion in Swift 3.1

I am converting Data bytes to sockaddr for getting sa_family_t
In ObjC, it is as below:
NSData * hostAddress;
- (sa_family_t)hostAddressFamily {
sa_family_t result;
result = AF_UNSPEC;
if ( (self.hostAddress != nil) && (self.hostAddress.length >= sizeof(struct sockaddr)) ) {
result = ((const struct sockaddr *) self.hostAddress.bytes)->sa_family;
}
return result;
}
In swift I am trying to convert it as below:
var hostAddress:Data?
private func hostAddressFamily() -> sa_family_t{
var result: sa_family_t = sa_family_t(AF_UNSPEC)
if (hostAddress != nil) && ((hostAddress?.count ?? 0) >= MemoryLayout<sockaddr>.size) {
// Generic parameter 'ContentType' could not be inferred
self.hostAddress!.withUnsafeBytes({ bytes in
bytes.withMemoryRebound(to: sockaddr.self, capacity: 1, {sockBytes in
result = sockBytes.pointee.sa_family
})
})
}
return result
}
Getting error : Generic parameter ‘ContentType’ could not be inferred
Look at the signature of Data.withUnsafeBytesType:
func withUnsafeBytes<ResultType, ContentType>(_ body: (Swift.UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType
This method is generic over ResultType and ContentType, and the ContentType is used in the argument of the closure body.
What compiler is trying to say is that it does not know what type bytes is of. Generally, to fix this type of errors, you'll want to annotate the type in the closure:
data.withUnsafeBytes { (_ bytes: UnsafePointer<...>) -> Void in ... }
Also, it's unlikely you'll need to bind the memory twice since NSData is untyped, and you already specifying a type to bind it to.
Putting it all together:
func hostAddressFamily() -> sa_family_t {
var result = sa_family_t(AF_UNSPEC)
guard
let hostAddress = hostAddress,
hostAddress.count >= MemoryLayout<sockaddr>.size
else {
return result
}
hostAddress.withUnsafeBytes { (_ bytes: UnsafePointer<sockaddr>) in
result = bytes.pointee.sa_family
}
return result
}

What is the equivalent for LinkedList<T> in Golang

In my use case, I would like to know how the following Java code would be implemented in Go
class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(){}
}
LinkedList<TreeNode> treeList = new LinkedList<TreeNode>();
I am able to import the container/list package and add an interface. But it is not allowing any generic object. Do I have to implement my own version of list with TreeNode struct?
I just need to know how LinkedList<T> would work in Go.
EDIT 1: To make it clear, I am adding the complete code here. I am trying to find the linked list of all nodes at each depth in a binary tree. I used two packages list and binary tree. You can find the source code for binarytree here and list here. list is same as container/list but I added few extra functions
package main
import (
"fmt"
"go/chapter02-linkedlists/list"
"go/chapter04-treesandgraphs/binarytree"
)
func main() {
inArr := []int{4, 5, 7, 8, 9}
t1 := binarytree.NewMinimalHeightBST(inArr, 0, len(inArr)-1)
binarytree.InOrderTraverse(t1)
var nodeList []*list.List
nodeList = getLevelbasedList(t1, 0)
fmt.Println()
for _, value := range nodeList {
fmt.Print("[ ")
for x := value.Front(); x != nil; x = x.Next() {
fmt.Print(x.Value.(int), " ")
}
fmt.Println("]")
}
}
func getLevelbasedList(root *binarytree.Tree, level int) []*list.List {
if root == nil {
return nil
}
var nodeList []*list.List
parents := list.New()
current := list.New()
current.PushFront(root)
for current.Len() > 0 {
nodeList = append(nodeList, current)
parents = current
current = list.New()
for x := current.Front(); x != nil; x = x.Next() {
node := x.Value.(*binarytree.Tree)
if node.Left != nil {
current = current.PushFront(node.Left)
}
if node.Right != nil {
current = current.PushFront(node.Right)
}
}
return nodeList
}
}
And the error is,
./question4_4b.go:56: cannot use current.PushFront((interface {})(node.Left)) (type *list.Element) as type *list.List in assignment
./question4_4b.go:59: cannot use current.PushFront((interface {})(node.Right)) (type *list.Element) as type *list.List in assignment
EDIT 2: Based on JamesHenstridge's comment I edited from
current = current.PushFront(node.Left)
to
current.PushFront(node.Left)
And the issue resolved. But now I am getting interface conversion error,
[ panic: interface conversion: interface is *binarytree.Tree, not int
goroutine 1 [running]:
Go doesn't support generic types (see FAQ question Why does Go not have generic types?).
You have to use Type assertions to obtain the typed value you want.
E.g. create your TreeNode type:
type TreeNode struct {
Data int
Left *TreeNode
Right *TreeNode
}
And to iterate over a list containing TreeNode values:
l := list.New()
// Populate list
for e := l.Front(); e != nil; e = e.Next() {
if tn, ok := e.Value.(TreeNode); ok {
// do something with tn which is of type TreeNode
fmt.Println(tn)
} else {
// e.Value is not of type TreeNode
}
}
If you assemble the list and you can be sure it only contains values of type TreeNode, you can omit the error check in the type assertion and it becomes like this:
for e := l.Front(); e != nil; e = e.Next() {
// if e.Value would not be of type TreeNode, run-time panic would occur
tn := e.Value.(TreeNode) // tn is of type TreeNode
fmt.Println(tn)
}
Edit:
The error you're getting:
cannot use current.PushFront((interface {})(node.Left)) (type *list.Element)
as type *list.List in assignment
At line:
current = current.PushFront(node.Left)
The current variable is of type list.List, and the method current.PushFront() returns a value of type *list.Element. These are 2 different types, you can't assign a *Element to a variable that has a type of List.
Edit 2:
Your 2nd error:
panic: interface conversion: interface is *binarytree.Tree, not int
Is caused by the line:
fmt.Print(x.Value.(int), " ")
You try to assert that the value x.Value is of type int but it isn't! x.Value is of type *binarytree.Tree so the assertion will obviously fail.

How is this chan leaked?

I'm trying to understand the problem outlined on this slide:
http://talks.golang.org/2013/bestpractices.slide#27
Copying the code in case the URL dies:
func sendMsg(msg, addr string) error {
conn, err := net.Dial("tcp", addr)
if err != nil {
return err
}
defer conn.Close()
_, err = fmt.Fprint(conn, msg)
return err
}
func broadcastMsg(msg string, addrs []string) error {
errc := make(chan error)
for _, addr := range addrs {
go func(addr string) {
errc <- sendMsg(msg, addr)
fmt.Println("done")
}(addr)
}
for _ = range addrs {
if err := <-errc; err != nil {
return err
}
}
return nil
}
func main() {
addr := []string{"localhost:8080", "http://google.com"}
err := broadcastMsg("hi", addr)
time.Sleep(time.Second)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("everything went fine")
}
And the comments:
the goroutine is blocked on the chan write
the goroutine holds a reference to the chan
the chan will never be garbage collected
I'm not sure I understand why the chan never gets collected or which goroutine is keeping a reference to the chan. Your time is appreciated!
The Go Programming Language Specification
Function literals
A function literal represents an anonymous function.
FunctionLit = "func" Function .
func(a, b int, z float64) bool { return a*b < int(z) }
A function literal can be assigned to a variable or invoked directly.
f := func(x, y int) int { return x + y }
func(ch chan int) { ch <- ACK }(replyChan)
Function literals are closures: they may refer to variables defined in
a surrounding function. Those variables are then shared between the
surrounding function and the function literal, and they survive as
long as they are accessible.
Send statements
A send statement sends a value on a channel. The channel expression
must be of channel type, the channel direction must permit send
operations, and the type of the value to be sent must be assignable to
the channel's element type.
SendStmt = Channel "<-" Expression .
Channel = Expression .
Both the channel and the value expression are evaluated before
communication begins. Communication blocks until the send can proceed.
A send on an unbuffered channel can proceed if a receiver is ready. A
send on a buffered channel can proceed if there is room in the buffer.
A send on a closed channel proceeds by causing a run-time panic. A
send on a nil channel blocks forever.
There is only one go statement, go func(addr string), and it's a closure over the channel variable errc.
func broadcastMsg(msg string, addrs []string) error {
errc := make(chan error)
for _, addr := range addrs {
go func(addr string) {
errc <- sendMsg(msg, addr)
fmt.Println("done")
}(addr)
}
for _ = range addrs {
if err := <-errc; err != nil {
return err
}
}
return nil
}
Two goroutines are started since len(addrs) == 2. Because of a premature exit when err != nil on the first receive on channel errc, only one goroutine completes. The second goroutine is blocked on the send (write) to the unbuffered channel errc; it never completes. Therefore, there is still a reference to errc, so it's never garbage collected. The second goroutine is eventually abandoned when the program exits.

Idiomatic way to do conversion/type assertion on multiple return values in Go

What is the idiomatic way to cast multiple return values in Go?
Can you do it in a single line, or do you need to use temporary variables such as I've done in my example below?
package main
import "fmt"
func oneRet() interface{} {
return "Hello"
}
func twoRet() (interface{}, error) {
return "Hejsan", nil
}
func main() {
// With one return value, you can simply do this
str1 := oneRet().(string)
fmt.Println("String 1: " + str1)
// It is not as easy with two return values
//str2, err := twoRet().(string) // Not possible
// Do I really have to use a temp variable instead?
temp, err := twoRet()
str2 := temp.(string)
fmt.Println("String 2: " + str2 )
if err != nil {
panic("unreachable")
}
}
By the way, is it called casting when it comes to interfaces?
i := interface.(int)
You can't do it in a single line.
Your temporary variable approach is the way to go.
By the way, is it called casting when it comes to interfaces?
It is actually called a type assertion.
A type cast conversion is different:
var a int
var b int64
a = 5
b = int64(a)
func silly() (interface{}, error) {
return "silly", nil
}
v, err := silly()
if err != nil {
// handle error
}
s, ok := v.(string)
if !ok {
// the assertion failed.
}
but more likely what you actually want is to use a type switch, like-a-this:
switch t := v.(type) {
case string:
// t is a string
case int :
// t is an int
default:
// t is some other type that we didn't name.
}
Go is really more about correctness than it is about terseness.
Or just in a single if:
if v, ok := value.(migrater); ok {
v.migrate()
}
Go will take care of the cast inside the if clause and let you access the properties of the casted type.
template.Must is the standard library's approach for returning only the first return value in one statement. Could be done similarly for your case:
func must(v interface{}, err error) interface{} {
if err != nil {
panic(err)
}
return v
}
// Usage:
str2 := must(twoRet()).(string)
By using must you basically say that there should never be an error, and if there is, then the program can't (or at least shouldn't) keep operating, and will panic instead.