# Using functional options instead of method

**URL:** <https://forum.golangbridge.org/t/using-functional-options-instead-of-method/19194>\
**Category:** Getting Help\
**Created:** [June 2, 2020, 6:05am UTC](https://forum.golangbridge.org/t/using-functional-options-instead-of-method/19194 "2020-06-02T06:05:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hyousef](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/hyousef/32/9127_2.png) [@hyousef](https://forum.golangbridge.org/u/hyousef)\
**Post date:** [June 2, 2020, 6:05am UTC](https://forum.golangbridge.org/t/using-functional-options-instead-of-method/19194/1 "2020-06-02T06:05:48Z")

</div>

I tried the below, and it worked well:

```go
package main

import "fmt"

type T interface {
}

type hashMap struct {
	m map[T]T
	k []T
}

func (h *hashMap) From(m map[T]T) {
	h.m = m
	h.k = make([]T, len(m))
	i := 0
	for key := range m {
		h.k[i] = key
		i++
	}
}

func main() {
	inv := new(hashMap)
	inv.From(map[T]T{"first": 1})
	fmt.Printf("%v", inv)
}

```

The output was correct as expected:

```bash
&{map[first:1] [first]}

```

I’m looking for a way where I can write:

```go
inv := new(hashMap).from(map[T]T{"first": 1})
// instead of:
//	inv := new(hashMap)
//	inv.From(map[T]T{"first": 1})

```

So, I re-wrote the code as below:

```go
package main

import "fmt"

type T interface {
}

type hashMap struct {
	m map[T]T
	k []T
	from func(m map[T]T) hashMap // <---- new
} 

func from(m map[T]T) hashMap { // <----- change of func signature
	h := new(hashMap)
	h.m = m
	h.k = make([]T, len(m))
	i := 0
	for key := range m {
		h.k[i] = key
		i++
	}
	return *h
}

func main() {
	inv := new(hashMap).from(map[T]T{"first": 1})
	fmt.Printf("%v", inv)
}

```

But I got the below output:

```bash
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x49c2c2]

goroutine 1 [running]:
main.main()
	d:/goplay/hashmap.go:55 +0xf2
exit status 2

```

Any idea how to get it done the way I’m looking for?

---

<div class="post-metadata">

**Author:** ![system](https://forum.golangbridge.org/uploads/default/original/2X/5/5ad234f7c3dbc68b6cc72d338ce4f2973d9fd81c.png) [@system](https://forum.golangbridge.org/u/system)\
**Post date:** [August 31, 2020, 6:05am UTC](https://forum.golangbridge.org/t/using-functional-options-instead-of-method/19194/2 "2020-08-31T06:05:50Z")

</div>

Closed on August 31, 2020, 6:05am UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
