I'm using SBT 0.12.0.
I've two tasks in my project/Build.scala - helloTask and u2 defined as follows:
val hello = TaskKey[Unit]("hello", "Prints 'Hello World'")
val helloTask = hello := {
println("Hello World")
}
val u2Task = TaskKey[Unit]("u2") := { println("u2") }
How to make u2 task depend on hellotask? I used <<= following the sample as described in Tasks (in the original version of the question it was https://github.com/harrah/xsbt/wiki/Tasks, but the doc has since moved and changed).
u2Task <<= u2Task dependsOn helloTask
But I got reassignment to val error. Apparently, I cannot get anything with <<= to work. What am I doing wrong?
I don't see you following the sample very closely - this works for me:
val helloTask = TaskKey[String]("hello")
val u2Task = TaskKey[Unit]("u2")
helloTask := {
println("Hello World")
"Hello World"
}
u2Task := {println("u2")}
u2Task <<= u2Task.dependsOn (helloTask)
The precise reason is that your definition of u2Task has a different type, you can see in the REPL:
scala> val u2Task = TaskKey[Unit]("u2")
u2Task: sbt.TaskKey[Unit] = sbt.TaskKey$$anon$3#101ecc2
scala> val u2Task = TaskKey[Unit]("u2") := {println("u2")}
u2Task: sbt.Project.Setting[sbt.Task[Unit]] = setting(ScopedKey(Scope(This,This,This,This),u2))
I got it to work. I misunderstood the <<= and := operators as assignment operators.
val hello = TaskKey[Unit]("hello", "Prints 'Hello World'")
val helloTask = hello := {
println("Hello World")
}
val u2 = TaskKey[Unit]("u2", "print u2")
val u2Task = u2 <<= hello map {_ => println("u2")}
and the result
> u2
Hello World
u2
Related
I have this func:
func getStringRepresentation(v interface{}, size int, brk bool, depth int) string {
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
v = *v.(types.Pointer) // does not work
val = reflect.ValueOf(v)
}
// ...
}
how can I dereference the pointer to get the value of it? When I use:
v = *v.(types.Pointer)
The error says:
Invalid indirect of 'v.(types.Pointer)' (type 'types.Pointer')
I tried this:
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
v = v.(types.Pointer).Underlying()
val = reflect.ValueOf(v)
}
and I tried this too:
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
v = val.Elem()
val = reflect.ValueOf(v)
}
I need to get the value of the interface{} from the pointer.
You can dereference pointers using reflect using Elem:
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
After the if statement, val is a reflect.Value representing the value passed in by the interface. If the value passed in is a pointer, val now has the dereferenced value of that pointer.
You have to use 'Elem' for access value referenced by Pointer.
package main
import (
"fmt"
"reflect"
)
func main() {
p := &struct{Hello string}{"world"}
v := reflect.ValueOf(p)
ps := v.Interface().(*struct{Hello string})
fmt.Println(ps)
s := v.Elem().Interface().(struct{Hello string})
fmt.Println(s)
}
Looks like this accomplished what I was trying to do:
func getStringRepresentation(v interface{}, size int, brk bool, depth int) string {
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
v = val.Elem().Interface() // gets the actual interface from the pointer
val = reflect.ValueOf(v) // gets the value of the actual interface
}
// ...
}
thanks to the other answers which I stole the eventual solution from.
I have a reference to a functionthat needs a parameter.
fun foo(x: Int) = 2 * x
val f: KFunction1<Int, Int> = ::foo
Is there any way to write applyArgument where
val f2: KFunction0<Int> = f1.applyArgument(42)
assertEquals("foo", f2.name)
assertEquals(84, f2())
I don't want to use a callable reference, as I need access to the name property.
hope it helps you:
fun foo(x: Int) = 2 * x
val f1 = ::foo
val f0 = { -> f1(42) }
f0() //84
KFunctions are intented to represent functions that are explicitly decleared in Kotlin code, but f2 is not declared anywhere in the code. In addition KFunction has lot of reflection properties and functions which are not relevant to the applied function f2. Therefore even if it is possible it is not recommended.
If you want to do it anyway you can simply write an applyArgument function in this way:
fun <T, R> KFunction1<T, R>.applyArgument(value: T): KFunction0<R> {
return object : KFunction<R> by this, KFunction0<R> {
override fun invoke(): R {
return this#applyArgument(value)
}
}
}
But, if what you need is to preserve the name, I would do it in a safe way. One way could be:
data class Named<out T>(val name: String, val value: T)
fun <T, R> Named<T>.map(transform: (T) -> R): Named<R> = Named(name, transform(value))
val <F : KFunction<*>> F.named: Named<F>
get() = Named(name, this)
Then use it:
fun foo(x: Int) = 2 * x
val f: Named<(Int) -> Int> = ::foo.named
val f2: Named<() -> Int> = f.map { fValue -> { fValue(42) } }
assertEquals("foo", f2.name)
assertEquals(84, f2.value())
Partial application is possible.
You may just declare a function for partial application and use it for the :: reference.
Hence, the name would not be the original function. Another approach - create your own classes/interfaces
data class MyFunction1<T, R>(val name: String, val f: (T) -> R) {
operator fun invoke(t: T) = f(t)
}
data class MyFunction0<R>(val name: String, val f: () -> R) {
operator fun invoke() = f()
}
Now define the curring:
fun MyFunction1<T, R>.curry(t: T) = MyFunction0(name){ f(t) }
(it can be a member function too)
I am trying to reflect a slice of pointers on a struct stored in an interface{}
I think I am doing ok until it's time to introspect the content on the pointed struct.
See the below example
package main
import (
"fmt"
"reflect"
)
type teststruct struct {
prop1 string
prop2 string
}
func main() {
test := teststruct{"test", "12"}
var container interface{}
var testcontainer []*teststruct
testcontainer = append(testcontainer, &test)
container = testcontainer
rcontainer := reflect.ValueOf(container)
fmt.Println(rcontainer.Kind())
rtest := rcontainer.Index(0).Elem()
fmt.Println(rtest)
rteststruct := reflect.ValueOf(rtest)
fmt.Println(rteststruct.Kind())
typeOfT := rteststruct.Type()
for i := 0; i < rteststruct.NumField(); i++ {
f := rteststruct.Field(i)
fmt.Printf("%d: %s %s = %v\n", i, typeOfT.Field(i).Name, f.Type(), f.String())
}
}
Which results
slice
{test 12}
struct
0: typ *reflect.rtype = <*reflect.rtype Value>
1: ptr unsafe.Pointer = <unsafe.Pointer Value>
2: flag reflect.flag = <reflect.flag Value>
I am definitely missing something here, someone would be able to explain me what ?
rtest := rcontainer.Index(0).Elem() is already the value, so when you do this: rteststruct := reflect.ValueOf(rtest), you are actually getting a reflect.Value which is of course a struct.
Replace the end of your code with this:
typeOfT := rtest.Type()
for i := 0; i < rtest.NumField(); i++ {
f := rtest.Field(i)
fmt.Printf("%d: %s %s = %v\n", i, typeOfT.Field(i).Name, f.Type(), f.String())
}
Playground
I'm confused because there seem to be two ways to initialize a pointer to a struct in the go language and they appear to me to be somewhat opposite in logic.
var b *Vertex
var c &Vertex{3 3}
Why does one use a * and the other use a & if b and c have the same resulting type? My apologies for not adequately understanding the posts already up related to this topic.
I am also not yet straight on the implications of "receivers" in this context. The terminology I am familiar with is "reference to (a)" or "pointer to (a)" or "address of (a)" and "de-reference of" or "value at address".
Thanks in advance for your help.
There are a number of ways to declare a pointer to a struct and assign values to the struct fields. For example,
package main
import "fmt"
type Vertex struct {
X, Y float64
}
func main() {
{
var pv *Vertex
pv = new(Vertex)
pv.X = 4
pv.Y = 2
fmt.Println(pv)
}
{
var pv = new(Vertex)
pv.X = 4
pv.Y = 2
fmt.Println(pv)
}
{
pv := new(Vertex)
pv.X = 4
pv.Y = 2
fmt.Println(pv)
}
{
var pv = &Vertex{4, 2}
fmt.Println(pv)
}
{
pv := &Vertex{4, 2}
fmt.Println(pv)
}
}
Output:
&{4 2}
&{4 2}
&{4 2}
&{4 2}
&{4 2}
References:
The Go Programming Language Specification
Variable declarations
Short variable declarations
Address operators
Allocation
Composite literals
Receivers are used for methods. For example, v is the receiver for the Vertex Move Method.
package main
import "fmt"
type Vertex struct {
X, Y float64
}
func NewVertex(x, y float64) *Vertex {
return &Vertex{X: x, Y: y}
}
func (v *Vertex) Move(x, y float64) {
v.X = x
v.Y = y
}
func main() {
v := NewVertex(4, 2)
fmt.Println(v)
v.Move(42, 24)
fmt.Println(v)
}
Output:
&{4 2}
&{42 24}
References:
The Go Programming Language Specification
Method sets
Method declarations
Calls
Method expressions
Method values
var c = &Vertex{3, 3} (you do need the =) is declaring a struct and then getting the reference to it (it actually allocates the struct, then gets a reference (pointer) to that memory).
var b *Vertex is declaring b as a pointer to Vertex, but isn't initializing it at all. You'll have a nil pointer.
But yes, the types are the same.
You can also do:
var d *Vertex
d = &Vertex{3,3}
In addition to what Wes Freeman mentioned, you also asked about receivers.
Let say you have this:
type Vertex struct {
}
func (v *Vertex) Hello() {
... do something ...
}
The Vertex struct is the receiver for the func Hello(). So you can then do:
d := &Vertex{}
d.Hello()
I have a struct that looks like:
type inv struct {
ID int `json:"id"`
Name string `json:"name"`
}
I'm querying some data from the database(assuming there are no errors):
rows, err := db.Query("select id, name from inv_table")
Normally, I'd have to pull the data from the row by scanning
var i inv
for rows.Next() {
rows.Scan(&i.ID, &i.Name)
}
I think this might work (to be tested tomorrow):
var i inv
for rows.Next() {
var x []interface{} = [&i.ID, &i.Name]
rows.Scan(x... )
}
In actuality I have many more columns in the result set from the query.
rows.Scan(&i)
or at least:
rows.Scan(getExportedValuePointers(&i)... )
I suppose I could always write some sort of encoder, however, it seems to me that there should be something in the box already.
** I realize that I could always write some reflection code similar to the encode/xml or encode/json ... but I'm hoping that someone has already done it.
UPDATE: The following code works as expected but not as I want:
package main
import "fmt"
type inv struct {
A int
B string
}
func main() {
var i inv
fmt.Printf("hello\n")
n, err := fmt.Sscan("1 c", &i.A, &i.B)
fmt.Printf("retval: %d %#v\n", n, err)
fmt.Printf("retval: %d, %s, %d %#v\n", i.A, i.B, n, err)
j := []interface{}{&i.A, &i.B}
k := []interface{}{i.A, i.B}
n, err = fmt.Sscan("2 d", j... )
fmt.Printf("retval: %d, %s, %d %#v\n", i.A, i.B, n, err)
fmt.Printf("retval: %d, %s\n", k... )
}
If you're looking for a package that will automatically bind your SQL query to your "inv" struct then take a look at gorp:
https://github.com/coopernurse/gorp
There is nothing to do this automatically, but you could write a function using the reflect package to do it.