Skip to content

Fixed bug in New function in list.go #239

@suwakei

Description

@suwakei

Proposal

When initializing list items, the address of the loop variable item was set to all elements of the slice, so all elements pointed to the value of the last item.

Expected Effect

Each item now points to an independent interface{} value. This allows pointer comparisons in the Index() method, for example, to function correctly.

list/list.go

func New(items interface{}, size int) (*List, error) {
	slice := reflect.ValueOf(items)
	values := make([]*interface{}, slice.Len())

---	for i := range values {
---		item := slice.Index(i).Interface()
---		values[i] = &item
+++	// Each item from the input slice is wrapped in an interface{},
+++	// and a pointer to this interface{} is stored. This ensures that
+++	// each element in `values` points to a unique interface{} holding the item's value.
+++	for i := 0; i < slice.Len(); i++ {
+++		val := slice.Index(i).Interface()
+++		values[i] = new(interface{}) // Allocate new memory for an interface{}
+++		*values[i] = val             // Store the item's value in the new interface{}
	}

	return &List{size: size, items: values, scope: values}, nil
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions