capture spaced user input - user-input

I am trying to capture user input in Go with little luck. I can get non-spaced words to work:
var s string
println("enter string:")
fmt.Scan(&s)
However, the Go documentation says that scan will delimit at spaces and new lines. So I think I have to set up bufio.Reader's ReadLine. Here is my attempt, which will not compile:
package main
import (
"bufio"
"os"
"fmt"
)
const delim = '\n'
const file = "file"
func main() {
r := bufio.NewReader() *Reader
println("enter string:")
line, err := r.ReadString(delim)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(line)
}
errors:
1.go:14: not enough arguments in call to bufio.NewReader
1.go:14: undefined: Reader
So, how do I define "Reader"? And if it was defined, would this be the correct way to capture the input as a string, delimited at "\n", and not at the space? Or should I be doing something completely different?
Thanks in advance.

Change
r := bufio.NewReader() *Reader
to read
r := bufio.NewReader(os.Stdin)
to fix the problem.
The original encantation is incorrect because you seem to just copied and pasted the method's signature from the spec, but the spec defines the signature, not an example of a call, so *Reader in there is the method's return type (the type your variable r will have). And the method's sole argument is defined to be rd io.Reader; that interface is conveniently implemented by the os.Stdin symbol which seems like a perfect match for your task.
P.S.
Consider reading all the docs in the "Learning Go" documentation section, especially "Effective Go".

If you look at the documentation for bufio.NewReader, it takes an argument of type io.Reader (which makes sense, because it takes a normal reader and makes it buffered, similar to java.io.BufferedReader in Java, which also takes a Reader argument). What is io.Reader? Looking at its documentation, it is an interface, specifying anything that has a Read method. Many types have a Read method; most commonly, *os.File. So you can construct a File using os.Open etc.
f, _ := os.Open(file)
r := bufio.NewReader(f)

Related

What are the semantics of input variables passed by reference?

Beckhoff's TwinCat-3, as well as Codesys 3 it's based on, adds references as an extension to IEC-61131-3 languages. I'm wondering what is the exact grammar and semantics of this non-standard addition (that's the problem with them: nobody bothers documenting them as well as a standard would).
It the following F_IsNonEmpty function valid and doing what one would expect, when invoked from the F_Test test function below?
FUNCTION F_IsNonEmpty : BOOL
VAR_INPUT
text : REFERENCE TO STRING;
END_VAR
F_IsNonEmpty := LEN(text) > 0;
END_FUNCTION
FUNCTION F_Test1
VAR
testMessage : STRING := '123';
END_VAR
IF F_IsNonEmpty(text := testMessage) THEN
{...}
END_IF
END_FUNCTION
Given that the target of the reference must be initialized using the REF= operator (v.s. e.g. C++ where reference targets are immutable), I'd have expected that the following invoking code would be correct instead - but it doesn't even compile:
FUNCTION F_Test2
VAR
testMessage : STRING := '123';
END_VAR
IF F_IsNonEmpty(text REF= testMessage) THEN
{...}
END_IF
END_FUNCTION
It seems that F_Test1 works correctly, but I'd like someone who actually uses Codesys 3 or TwinCat-3 REFERENCE TO feature to confirm.
When you use a REFERENCE in a VAR_INPUT, it's as if you were using a VAR_IN_OUT variable.
Otherwise if you declare your REFERENCE in the VAR section, you need to use REF= when assigning another variable to it (or get an exception).
In essence, REFERENCE (like a VAR_IN_OUT var) is a more convenient and "safe" pointer because the dereference operator ^ is not needed and because the type is checked at compile time.

Abstracting PSQL Write Query

I have a typical function that takes a post request from the frontend and decodes the data into a struct in order to put it into a psql database. You can see the code below. My problem is that I want to be able to abstract this function so that I can give it any amount of variables of any type so that for every request I don't have to have a separate write handler.
It looks difficult because I would have to somehow pass in a way to abstract var profitReq profitReq to work for any struct. If golang had some sort of eval string method I would know how to do this, but someone correct me if I'm wrong, but I don't think that it does.
The other place I need to change is in QueryRow - I have to be able to pass it in a variable number of variables. I could construct the string easily enough, but I'm not sure how to append variables to that QueryRow necessarily. If I append all the variables to an array for example, I can't pass that array into QueryRow as that's not how it's structured. Again, here some sort of eval statement would help.
I'm new to golang, but I've seen a lot of cool things related to interfaces, which I admittedly don't understand very well. Would there be a way to use an interface here that would help?
Thanks to anyone who can help!
func Write_profit_table(profitWriteChannel chan string, profitType string, req *http.Request) {
var profitReq profitReq;
err := json.NewDecoder(req.Body).Decode(&profitReq);
if err!=nil{
log.Panic(err)
}
NotInDB, _ := Search_userinfo_table(profitReq.Email)
if NotInDB == false {
var lastInsertId int
err2 := db.QueryRow("INSERT INTO profit(email, type, dateArray, amount, interest, compounded, recurring, name, description, profitFrom)
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) returning uid;",
profitReq.Email, profitReq.Type, pq.Array(profitReq.DateArray), profitReq.Profit, profitReq.Interest,
profitReq.Compounded, profitReq.Recurring, profitReq.Name, profitReq.Description, profitReq.ProfitFrom).Scan(&lastInsertId);
if err2!=nil{
log.Panic(err2)
}
}
profitWriteChannel<-"finished writing to profit"
}
The feature you're looking for is called generics.
Generics are not supported by Go 1.x
Luckily for us, there's a proposal for them for Go 2 (called Contracts)
What can you do until then?
Duplicate your code (probably what you're doing now)
Use interfaces
If you know that this method will always query by email, you could create simple interface for that purpose: type Emailer interface { Email() string }
Use empty interface (interface{}) and reflection to figure out what columns you have.
Write your own generator. A bit like (1), but you don't have to do this yourself.
Here's the gist of it:
https://play.golang.org/p/A_2YKWLvmn-

Type wrapping of non-atomic types in golang

I'm new to golang and am trying to understand a code example of type wrapping for the "non-atomic" type time.Time.
The type extension in question is from the Go client for GDAX on github, go-coinbase-exchange project.
The expected behavior would be for Time variables from the project (coinbase.Time), which are of type Time time.Time (as defined in the project's time.go file) to behave something like the following example for extending the "atomic" type int (from blog.riff.org in that they might follow a kind of "inheritance" from the base type for functions like Time.format (from golang's standard implementation of time:
package main
import "fmt"
type Int int
func (i Int) Add(j Int) Int {
return i + j
}
func main() {
i := Int(5)
j := Int(6)
fmt.Println(i.Add(j))
fmt.Println(i.Add(j) + 12)
}
But if I modify the code example from the project's List Account Ledger example found in Readme.md to include a print function which might otherwise give me a human-readable view of the CreatedAt struct variables (as follows), I get a compiler error saying that "type coinbase.Time has no field or method Format":
for _, e := range ledger {
print("Entry Creation: ")
fmt.Printf(e.CreatedAt.Format("2006-01-02 15:04:05.999999+00"))
}
The expected behavior inside the for loop would be for it to print the ledger entries in a human-readable format. I can get the contents of the structs, but I'm not really sure how to then use the resulting wall, ext and loc members.
For example, inserting fmt.Printf("%#v", e.CreatedAt) into the for loop gives me a representation of the time that looks something like this:
coinbase.Time{wall:0x3015a123, ext:63612345678, loc:(*time.Location)(nil)}
{806986000 63638738354 <nil>}
I can also see that wall is of type uint64, that ext is of type int64 and that loc is just GMT/UTC=0 by formatting the variable as a string because fmt.Printf("%s", e.CreatedAt) gives me output which is similar to the following:
{%!s(uint64=712345678) %!s(int64=63612345678) %!s(*time.Location=<nil>)}
It seems like I'm missing something. I've requested further information through issues tab on github, but maybe this is a nube question. So I'm not sure how quick the response time would be, and I'm interested in the more general case for extending non-atomic types in go.
Named types do not inherit any methods from the underlying type (indeed there is no inheritance at all in Go); you must cast to the underlying type to call any methods from that type:
(time.Time(e.CreatedAt)).Format("2006-01-02 15:04:05.999999+00")

What does the tt metavariable type mean in Rust macros?

I'm reading a book about Rust, and start playing with Rust macros. All metavariable types are explained there and have examples, except the last one – tt. According to the book, it is a “a single token tree”. I'm curious, what is it and what is it used for? Can you please provide an example?
That's a notion introduced to ensure that whatever is in a macro invocation correctly matches (), [] and {} pairs. tt will match any single token or any pair of parenthesis/brackets/braces with their content.
For example, for the following program:
fn main() {
println!("Hello world!");
}
The token trees would be:
fn
main
()
∅
{ println!("Hello world!"); }
println
!
("Hello world!")
"Hello world!"
;
Each one forms a tree where simple tokens (fn, main etc.) are leaves, and anything surrounded by (), [] or {} has a subtree. Note that ( does not appear alone in the token tree: it's not possible to match ( without matching the corresponding ).
For example:
macro_rules! {
(fn $name:ident $params:tt $body:tt) => { /* … */ }
}
would match the above function with $name → main, $params → (), $body → { println!("Hello world!"); }.
Token tree is the least demanding metavariable type: it matches anything. It's often used in macros which have a “don't really care” part, and especially in macros which have a “head” and a “tail” part. For example, the println! macros have a branch matching ($fmt:expr, $($arg:tt)*) where $fmt is the format string, and $($arg:tt)* means “all the rest” and is just forwarded to format_args!. Which means that println! does not need to know the actual format and do complicated matching with it.

; expected but <place your favourite keyword here> found

I'm trying to write a class for a scala project and I get this error in multiple places with keywords such as class, def, while.
It happens in places like this:
var continue = true
while (continue) {
[..]
}
And I'm sure the error is not there since when I isolate that code in another class it doesn't give me any error.
Could you please give me a rule of thumb for such errors? Where should I find them? are there some common syntactic errors elsewhere when this happens?
It sounds like you're using reserved keywords as variable names. "Continue", for instance, is a Java keyword.
You probably don't have parentheses or braces matched somewhere, and the compiler can't tell until it hits a structure that looks like the one you showed.
The other possibility is that Scala sometimes has trouble distinguishing between the end of a statement with a new one on the next line, and a multi-line statement. In that case, just drop the ; at the end of the first line and see if the compiler's happy. (This doesn't seem like it fits your case, as Scala should be able to tell that nothing should come after true, and that you're done assigning a variable.)
Can you let us know what this code is inside? Scala expects "expressions" i.e. things that resolve to a particular value/type. In the case of "var continue = true", this does not evaluate to a value, so it cannot be at the end of an expression (i.e. inside an if-expression or match-expression or function block).
i.e.
def foo() = {
var continue = true
while (continue) {
[..]
}
}
This is a problem, as the function block is an expression and needs to have an (ignored?) return value, i.e.
def foo() = {
var continue = true
while (continue) {
[..]
}
()
}
() => a value representing the "Unit" type.
I get this error when I forget to put an = sign after a function definition:
def function(val: String):Boolean {
// Some stuff
}