Functions as the struct fields or as struct methods - function

Could anybody help me to clarify in which situations is better to use functions as the struct fields and when as the methods of struct?

A field of function type is not a method, so it's not part of the method set of the struct type. A "true" method declared with the struct type as the receiver will be part of the method set.
That being said, if you want to implement an interface, you have no choice but to define "true" methods.
Methods are "attached" to concrete types and cannot be changed at runtime. A field of function type may be used to "mimic" virtual methods, but as said above, this is not a method. A field of function type may be reassigned at runtime.
Like in this example:
type Foo struct {
Bar func()
}
func main() {
f := Foo{
Bar: func() { fmt.Println("initial") },
}
f.Bar()
f.Bar = func() { fmt.Println("changed") }
f.Bar()
}
Which outputs (try it on the Go Playground):
initial
changed
Fields of function type are often used to store callback functions. Examples from the standard lib are http.Server and http.Transport.

Related

Can I create an alias for a generic function? I get error "Cannot use generic function without instantiation"

I can define a generic function:
package hello
func IsZero[T int64|float64](value T) bool {
return value == 0
}
Then if I try to alias that function in another package, it fails:
package world
import "hello"
var IsZero = hello.IsZero
The above doesn't compile with:
cannot use generic function hello.IsZero without instantiation
Instead this works:
var IsZero = hello.IsZero[int64]
Is it possible to do this, using some other syntax?
That's not an alias. And you already have your answer, actually. But if you want a formal reference, from the language specs, Instantiations:
A generic function that is is not called requires a type argument list for instantiation
So when you attempt to initialize a variable of function type, the function hello.IsZero is not called, and therefore requires instantiation with specific type parameters:
// not called, instantiated with int64
var IsZero = hello.IsZero[int64]
At this point the variable (let's give it a different name for clarity) zeroFunc has a concrete function type:
var zeroFunc = IsZero[int64]
fmt.Printf("type: %T\n", zeroFunc)
Prints:
type: func(int64) bool
This might or might not be what you want, as this effectively monomorphises the function.
If you just want to have a local symbol, with the same implementation (or a tweaked version thereof), declaring a "wrapper" function works. Just remember that the type parameters of your wrapper can only be as strict or stricter than the wrapped one's
E.g. Given
IsZero[T int64 | float64](v T)
your wrapper can not be
WrapIsZeroPermissive[T int64 | float64 | complex128](v T) bool {
return IsZero(v) // does not compile, T's type set is a superset
}
but can be
WrapIsZeroStricter[T int64](v T) bool {
return IsZero(v) // ok, T's type set is a subset
}
If the function is small, like in the question, it's probably easier to just vendor it:
package vendor
func thisIsJustCopy[T int64|float64](value T) bool {
return value == 0
}
but if the function is big, you can do it like this:
package world
import "hello"
func IsZero[T int64|float64](value T) bool {
return hello.IsZero(value)
}
I try to alias that function in another package
Aliases work for types only. Your code just tries to declare a variable.
Is it possible to do this, using some other syntax?
No.

How to write a function that takes a slice of functions?

I am trying to write a function that takes a slice of functions. Consider the following simple illustration:
fn g<P: Fn(&str) -> usize>(ps: &[P]) { }
fn f1() -> impl Fn(&str) -> usize { |s: &str| s.len() }
fn f2() -> impl Fn(&str) -> usize { |s: &str| s.len() }
fn main() {
g(&[f1(), f2()][..]);
}
It fails to compile:
error[E0308]: mismatched types
--> src/main.rs:6:15
|
6 | g(&[f1(), f2()][..]);
| ^^^^ expected opaque type, found a different opaque type
|
= note: expected type `impl for<'r> std::ops::Fn<(&'r str,)>` (opaque type)
found type `impl for<'r> std::ops::Fn<(&'r str,)>` (opaque type)
Is there any way to do this?
Your problem is that every element of the array must be of the same type, but the return of a function declared as returning impl Trait is an opaque type, that is an unspecified, unnamed type, that you can only use by means of the given trait.
You have two functions that return the same impl Trait but that does not mean that they return the same type. In fact, as your compiler shows, they are different opaque types, so they cannot be part of the same array. If you were to write an array of values of the same type, such as:
g(&[f1(), f1(), f1()]);
then it would work. But with different functions, there will be different types and the array is impossible to build.
Does that mean there is no solution for your problem? Of course not! You just have to invoke dynamic dispatch. That is you have to make your slice of type &[&dyn Fn(&str) -> usize]. For that you need to do two things:
Add a level of indirection: dynamic dispatching is always done via references or pointers (&dyn Trait or Box<dyn Trait> instead of Trait).
Do an explicit cast to the &dyn Trait to avoid ambiguities in the conversion.
There are many ways to do the cast: you can cast the first element of the array, or you can declare the temporary variables, or give the slice a type. I prefer the latter, because it is more symmetric. Something like this:
fn main() {
let fns: &[&dyn Fn(&str) -> usize] =
&[&f1(), &f2()];
g(fns);
}
Link to a playground with this solution.

What are the differences between functions and methods in Swift?

I always thought functions and methods were the same, until I was learning Swift through the "Swift Programming Language" eBook. I found out that I cannot use greet("John", "Tuesday") to call a function that I declared inside a class, as shown in the eBook in the screen shot below:
I received a error saying that "Missing argument label 'day:' in call" as per this screen shot:
Here is the code:-
import Foundation
import UIKit
class ViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//var dailyStatement = greet("John", "Tuesday")
var dailyStatement = greet("John", day: "Tuesday")
println(dailyStatement)
}
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
}
After some research, I found this post: Difference between a method and a function, and it seems to me that the function that I declared inside a class is actually called a method. So, the syntax that I use to call the method is different compared to the syntax that I use to call a function.
I never realized this difference when I was programming in Objective-C.
What are the differences between functions and methods in Swift?
When do we use functions and when do we use methods in Swift?
After a few hours of reading and experimenting, here are the things that I found out:-
Functions in Swift
Functions are self-contained chunks of code that perform a specific
task. You give a function a name that identifies what it does, and
this name is used to “call” the function to perform its task when
needed.
Resource: Official Apple Documentation on Functions in Swift
Function Parameter Names
However, these parameter names are only used within the body of the
function itself, and cannot be used when calling the function. These
kinds of parameter names are known as local parameter names, because
they are only available for use within the function’s body.
It means that by default, all the parameters for Function are local parameters.
But, sometimes we want to indicate the purpose of each parameter. So, we can actually define an external parameter name for each parameter. Example Code:
func someFunction(externalParameterName localParameterName: Int) {
// function body goes here, and can use localParameterName
// to refer to the argument value for that parameter
}
Another way to make the external parameter name is using hash symbol (#) to shorten the name.
func someFunction(#localParameterName: Int) {
// function body goes here, and can use localParameterName
// to refer to the argument value for that parameter
}
To call the above functions with external parameter, you may use
someFunction(localParameterName:10)
Methods in Swift
Methods are functions that are associated with a particular type.
Classes, structures, and enumerations can all define instance methods,
which encapsulate specific tasks and functionality for working with an
instance of a given type.
Resource: Official Apple Documentation on Methods in Swift
However, the default behavior of local names and external names is
different for functions and methods.
Specifically, Swift gives the first parameter name in a method a local
parameter name by default, and gives the second and subsequent
parameter names both local and external parameter names by default.
Code below shows the differences for default and non-default parameters for method in Swift.
import Foundation
import UIKit
class ViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Default methods calling
var dailyStatement = greet("Rick", day: "Tuesday")
println(dailyStatement)
//First parameter is also an external parameter
var dailyStatement2 = greet2(name:"John", day: "Sunday")
println(dailyStatement2)
}
//Default: First Parameter is the local parameter, the rest are external parameters
func greet (name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
//Use Hash symbol to make the First parameter as external parameter
func greet2 (#name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
}
I might miss some important details. Hope someone can provide a better answer.
As you said yourself, methods are functions, but in a class. In objective-c you never realized this, because we were only coding in classes. Every function that we wrote was a method of a class (ViewController or some other class we created).
In Swift we have the ability to create functions that are not inside some class. The main reason for doing this is to write functions that are not tied to any class, and can be used wherever we need them. So if you have a function that is related to a class you write it inside the class and you can access is from every instance of the class:
class Square {
var length: Double
func area() -> Double {
return length * length
}
}
But if you need to access the function from everywhere, then you don't write it inside a class. For example:
func squared(number: Int) -> Int {
return number * number
}
About your syntax issues between functions and methods: You guessed it right, methods and functions are called a little bit differently. That is because in Objective-C we had long method names and we liked them because we could read what the methods were doing and what the parameters were for. So the first parameter in a method is in most cases described by the function name itself. And the other parameters shouldn't only be some numbers or strings or instances, they should be described as well, so Swift writes the name of the variable automatically. If you want to describe it by yourself you can do that as well:
class Something {
func desc(firstString string1: String, secondString string2:String) {...}
}
Well, #Ricky's answer says it pretty much. I was confused what exactly they are. So here is my thought:
Functions could be defined outside of classes or inside of classes/structs/enums, while Methods have to be defined inside of and part of classes/structs/enums.
We could define a Function outside of any Type's definition and could use it within Methods of any Type's definition.
Just my understanding and illustration here, hope this helps someone else or you may edit if you feel there is an improvement needed OR let me know if anything is wrong:
//This is a Function which prints a greeting message based on the category defined in an 'enum'
func greet(yourName name: String, category: GreetingsCategory) {
switch category {
case .Person:
print("Hello, " + name + " Today is Tuesday")
case .Vehicle:
print("Hello, " + name + " your Vehicle is a Car")
}
}
//This is an 'enum' for greetings categories
enum GreetingsCategory: String {
case Person
case Vehicle
}
//Type: Person
class Person {
//This is a method which acts only on Person type
func personGreeting() {
greet(yourName: "Santosh", category: .Person)
}
}
//Type: Vehicle
class Vehicle {
//This is a method which acts only on Vehicle type
func vehicleGreeting() {
greet(yourName: "Santosh", category: .Vehicle)
}
}
//Now making use of our Function defined above by calling methods of defferent types.
let aPerson = Person()
aPerson.personGreeting()
//prints : Hello, Santosh Today is Tuesday
let aVehicle = Vehicle()
aVehicle.vehicleGreeting()
//prints: Hello, Santosh your Vehicle is a Car
//We can also call the above function directly
greet(yourName: "Santosh", category: .Person)
Mainly the names are used interchangeably without people having a real intent of distinguishing them. But ultimately they do have a difference.
someFile.swift:
func someFunc{
//some code
}
class someClass{
func someMethod{
//some code
}
}
Note: someClass != someFile
someMethod works only on its associated type which is 'someClass'. However the same can't be said for someFunc. someFunc is only in the someClass.Swift because semantically it is better suited to be written in that file. It could have been written in any other class as long as it's marked with private
And obviously the method can access self. With functions, there is no self.. For more see: What's the difference between a method and a function?
Here is a simple answer on the difference between functions and methods:
Some folks use “function” and “method” interchangeably, but there’s a
small difference: both of them are reusable chunks of code, but
methods belong to classes, structs, and enums, whereas functions do
not.
So:
func thisIsAFunction() {
}
struct Person {
func thisIsAMethod() {
}
}
Because methods always belong to a data type, they have a concept of
self that functions do not.
source: https://www.hackingwithswift.com/example-code/language/whats-the-difference-between-a-function-and-a-method
Lots of great answers, but let me use Xcode to show something visually from the UIKit module:
That is a function because it's written at the global level. It's not a method. Methods are scoped to a class.
Screenshot to show that it's at the global level.
The following function is at the global level:
public func UIApplicationMain(_ argc: Int32, _ argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>>!,
_ principalClassName: String?, _ delegateClassName: String?) -> Int32
Icons for the different symbols. (Class, Method, Property, Protocol, Function, Extensions are all different symbols)
The function has an icon like 𝓯
The method has an icon of M
functional principle as a part of functional language
function is a first-class type (first-class citizen) in Swift. Higher order functions
assign to a variable
pass as an argument
return
Function
Function is a block of code that is created for executing some task. Function consists of name, optional parameters(name, type), optional return type, body.
func name(parameterName1: Int, parameterName2: String) -> Bool {
//statements
return true
}
Function type - function’s parameter type + return type[Java about]. For example it is used as function's parameter
//Function type for the sample above
(Int, String) -> Bool
Method
Method - is a function which is associated with a type - class, structure, enum [About]:
Instance method - method which belongs to instance
MyClass().foo()
Type method - method which belongs to type itself. class or static is used[About]
MyClass.foo()
Closure
As official doc says that Closure in Swift has three next forms:
global function(with name, without capturing) - is a function that is declared in a global scope(out of class scope). Usually it is defined as a first level of .swift file and does not have a big memory foot print
nested function(with name, with capturing enclosing function variables) - function inside other function
closure expression(without name, with capturing enclosing context)
Closure(closure expression) - anonymous function - is a block of code(functionality). Closure is a type of function without name. Closure is a function in terms of Functional programming. It can support capturing concept(if it doesn't capture it is lambda). It is similar to block in Objective-C.
[Closure vs Lambda]
They can be used for:
non-escaping closure - sync operations - click events, sort...
escaping closure - async operations - e.g.completion handler - it is a callback/notification which is called when task is done
class ClassA {
var variable = "Hello"
func fooA() {
print(variable)
let b = ClassB() //1
b.fooB(completionHandler: { [weak self] (input) -> String? in //2 pass closure //3 capture list or any calls from closure to outher scope
guard let self = self else { return nil }
self.variable = "World" //capturing self.variable
return String(input)
})
}
}
class ClassB {
var myCompletionHandler: ((Int) -> String?)? = nil //5
func fooB(completionHandler: #escaping (Int) -> String?) { //4
self.myCompletionHandler = completionHandler //6
let result = completionHandler(7)
}
func fooB2(completionHandler: #escaping (Int) -> String?) { //if you re-pass function to #escaping function you must mark it by #escaping too
self.fooB(completionHandler: completionHandler)
}
}
func testClosure() {
ClassA().fooA()
}
(Int) -> String? //Function type
//Closure Expression
{ [weak self] (input) -> String? in
//logic
}
[non-escaping vs escaping closure]
[#autoclosure]
[Init/customize stored property by closure]
[JVM Memory model]

JSON and dealing with unexported fields

Is there a technical reason why unexported fields are not included by encoding/json? If not and it is an arbitrary decision could there be an additional back door option (say '+') to include even though unexported?
Requiring client code to export to get this functionality feels unfortunate, especially if lower case is providing encapsulation or the decision to marshal structures comes much later than design of them.
How are people dealing with this? Just export everything?
Also, doesn't exporting field names make it difficult to follow suggested idioms. I think if a struct X has field Y, you can not have an accessor method Y(). If you want to provide interface access to Y you have to come up with a new name for the getter and no matter what you'll get something un-idiomatic according to http://golang.org/doc/effective_go.html#Getters
There is a technical reason. The json library does not have the power to view fields using reflect unless they are exported. A package can only view the unexported fields of types within its own package
In order to deal with your problem, what you can do is make an unexported type with exported fields. Json will unmarshal into an unexported type if passed to it without a problem but it would not show up in the API docs. You can then make an exported type that embeds the unexported type. This exported type would then need methods to implement the json.Marshaler and json.Unmarshaler interfaces.
Note: all code is untested and may not even compile.
type jsonData struct {
Field1 string
Field2 string
}
type JsonData struct {
jsonData
}
// Implement json.Unmarshaller
func (d *JsonData) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, &d.jsonData)
}
// Getter
func (d *JsonData) Field1() string {
return d.jsonData.Field1
}
Stephen's answer is complete. As an aside, if all you really want is lowercase keys in your json, you can manually specify the key name as follows:
type Whatever struct {
SomeField int `json:"some_field"`
}
In that way, marshaling a Whatever produces the key "some_field" for the field SomeField (instead of having "SomeField" in your json).
If you're dead-set on keeping unexported fields, you can also implement the json.Marshaler interface by defining a method with the signature MarshalJSON() ([]byte, error). One way to do this is to use a struct literal that simply has exported versions of the unexported fields, like this:
type Whatever struct {
someField int
}
func (w Whatever) MarshalJSON() ([]byte, error) {
return json.Marshal(struct{
SomeField int `json:"some_field"`
}{
SomeField: w.someField,
})
}
That can be a bit cumbersome, so you can also use a map[string]interface{} if you prefer:
func (w Whatever) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"some_field": w.SomeField,
})
}
However it should be noted that marshaling interface{} has some caveats and can do things like marshal uint64 to a float, causing a loss of precision. (all code untested)

How does this Go function type "HandlerFunc" work, from the standard library "net/http"

I'm confused about this bit of code from the HTTP package:
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
Why does the ServeHTTP method have the exact same signature as it's type - what's the point?
Testing, I discovered that if I pass a random function (foo) to the HandlerFunc:
var bar = HandlerFunc(foo)
bar becomes an instance of HandlerFunc with foo as its ServeHTTP method. Now I'm really confused about how on earth this works.
If I have more than one methods on a type, how do I know which one is going to be attached to the new instance and with what name or order?
This approach allows you to use a function in a context that's expecting a Handler.
What happens is, there's a Handler interface:
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
and various functions are declared to accept parameters that are declared to belong to this interface — for example:
func TimeoutHandler(h Handler, ns int64, msg string) Handler {
f := func() <-chan int64 {
return time.After(ns)
}
return &timeoutHandler{h, f, msg}
}
What this means is that when you invoke such a function, you have to pass in an object belonging to a type that satisfies this interface, which is to say, a type that has a ServeHTTP method with the appropriate signature. (In Go, unlike some languages, a type doesn't need to explicitly implement an interface, it just needs to have the methods specified by the interface.)
So, the code-snippet that you quote:
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
creates a type HandlerFunc that's based on func(ResponseWriter, *Request), but augments the type with a method called ServeHTTP with an appropriate signature, so that it satisfies the Handler interface. This ServeHTTP method just calls the function itself. So, if f is a function with the right signature, you could write something like this:
var h HandlerFunc = f // h == f, but converted to a HandlerFunc
// so it satisfies the Handler interface.
TimeoutHandler(h, 1000000, "timed out")
To clarify a few things about this:
Testing, I discovered that if I pass a random function (foo) to the HandlerFunc:
var bar = HandlerFunc(foo)
bar becomes an instance of HandlerFunc with foo as its ServeHTTP method. Now I'm really confused about how on earth this works.
Firstly, it's more correct to say that you've converted a random function foo to type HandlerFunc, rather than that you've passed the function to HandlerFunc as though HandlerFunc were a function. (The HandlerFunc(foo) notation is a typecast; you could just as well write var bar HandlerFunc = foo and let the conversion happen implicitly.)
Secondly, it's more correct to say that bar has a ServeHTTP method that invokes foo, than that foo itself actually is the ServeHTTP method.
Does that make sense?